无法使用Beautifulsoup抓取内容

时间:2020-08-27 06:55:21

标签: python web-scraping beautifulsoup

我正在尝试删除此website,我用于剪贴网站的代码为

ua1 = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
ua2 = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome'
headers = {'User-Agent': ua2,
           'Accept': 'text/html,application/xhtml+xml,application/xml;' \
                     'q=0.9,image/webp,*/*;q=0.8'}
session = requests.Session()
response = session.get("website--link", headers=headers)
webContent = response.content


root_tag=["div", {"class": "qtxgkq-0"}]
image_tag=["img",{"":""},"src"]

bs = BeautifulSoup(webContent, 'lxml')
all_tab_data = bs.findAll(root_tag[0], root_tag[1])

output=[]
for div in all_tab_data:
    image_url = None
    div_img = str(div)
    match = re.search(r"(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png|jpeg)", div_img)
    if match!=None:
        image_url = match.group(0)
    else:
        image_url = div.find(image_tag[0],image_tag[1]).get(image_tag[2])
    if image_url!=None:
        if image_url[0] == '/' and image_url[1] != '/':
            image_url = main_url + image_url
    print(image_url)
    output.append(image_url)

我得到的清单是空的,尽管我选择了正确的标签。我还尝试将根标签更改为

root_tag=["div", {"class": "b01o18-0 kpPYYo"}]

仍然得到空列表

1 个答案:

答案 0 :(得分:1)

您的代码很好,但是您错过了重要的一部分。他们通过javascript渲染了网站的那部分,您的请求将不会执行;)您只得到了html。 但是数据在那里,而不仅仅是您期望的位置。它在脚本标签中作为json。

function tipPercentage(rating) {
  switch(rating) {
  case "terrible":
  case "poor": 
    return 3; break;
  case "good":
  case "great":
    return 10; break;
  case "excellent":
    return 20; break;
  default:
    return 0;
  }
}

然后从那里去。

import json
data = json.loads(bs.findAll('script', {'id': '__NEXT_DATA__'})[0].text)