BeautifulSoup4找不到div

时间:2018-03-11 22:47:57

标签: python web-scraping beautifulsoup

我最近一直在尝试使用BeautifulSoup4,并且已经在各种不同的网站上取得了相当不错的成功。虽然我在试图刮掉amazon.com时偶然发现了一个问题。

使用下面的代码,当打印'汤'时我可以看到div,但是当我搜索div本身时,BS4会返回null。我认为问题在于如何处理html。我试过LXML和html5lib。有什么想法吗?

import bs4 as bs
import urllib3

urllib3.disable_warnings()
http = urllib3.PoolManager()

url = 'https://www.amazon.com/gp/goldbox/ref=gbps_fcr_s-4_a870_dls_UPCM?gb_f_deals1=dealStates:AVAILABLE%252CWAITLIST%252CWAITLISTFULL,includedAccessTypes:GIVEAWAY_DEAL,sortOrder:BY_SCORE,enforcedCategories:2619533011,dealTypes:LIGHTNING_DEAL&pf_rd_p=56200e05-4eb2-42ca-9723-af0811ada870&pf_rd_s=slot-4&pf_rd_t=701&pf_rd_i=gb_main&pf_rd_m=ATVPDKIKX0DER&pf_rd_r=PQNZWZRKVD93HXXVG5A7&ie=UTF8'

original = http.request('Get',url)
soup = bs.BeautifulSoup(original.data, 'lxml')

div = soup.find_all('div', {'class':'a-row padCenterContainer'})

1 个答案:

答案 0 :(得分:1)

您可以使用selenium在抓取html之前加载javascript。

from bs4 import BeautifulSoup
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=options)

url = 'https://www.amazon.com/gp/goldbox/ref=gbps_fcr_s-4_a870_dls_UPCM?gb_f_deals1=dealStates:AVAILABLE%252CWAITLIST%252CWAITLISTFULL,includedAccessTypes:GIVEAWAY_DEAL,sortOrder:BY_SCORE,enforcedCategories:2619533011,dealTypes:LIGHTNING_DEAL&pf_rd_p=56200e05-4eb2-42ca-9723-af0811ada870&pf_rd_s=slot-4&pf_rd_t=701&pf_rd_i=gb_main&pf_rd_m=ATVPDKIKX0DER&pf_rd_r=PQNZWZRKVD93HXXVG5A7&ie=UTF8'
driver.get(url)
html = driver.page_source
soup = BeautifulSoup(html, 'lxml')

div = soup.find('div', {'class': 'a-row padCenterContainer'})
print(div.prettify())

此脚本的输出太长,无法提出此问题,但here is a link to it