[英]How to parse the data in <pre> tag using beautifulsoup?
當我嘗試從以下網站抓取數據時
我是從bedbathbeyond網站獲得的,如果我使用request和beautifulsoup,我什么也收不到。 這是為什么?
碼:
r = requests.get(url)
soup = BeautifulSoup(r.content,'lxml')
soup.find_all('span', class_ = 'BVRRReviewAbbreviatedText')
返回值為空:[]
我使用js2py
,因為materials
對象包含多個鍵( BVRRRatingSummarySourceID
, BVRRSecondaryRatingSummarySourceID
和BVRRSourceID
),並且如果需要全部內容,則很難通過正則表達式從其值中獲取HTML。
from bs4 import BeautifulSoup
import js2py
import requests
r = requests.get('https://bedbathandbeyond.ugc.bazaarvoice.com/2009-en_us/1061083288/reviews.djs?format=embeddedhtml')
pattern = (r'var'
r'\s+'
r'materials'
r'\s*=\s*'
r'{"BVRRRatingSummarySourceID".*}')
js_materials = re.search(pattern, r.text).group()
obj = js2py.eval_js(js_materials).to_dict()
html = obj['BVRRSourceID']
soup = BeautifulSoup(html, 'lxml')
spans = soup.select('span.BVRRReviewAbbreviatedText')
>>> len(spans)
5
在下面的示例中,我僅在BVRRSourceID
鍵下使用了HTML,但是您可以通過將值連接在一起來使用整個HTML:
html = ''.join(obj.values())
如果要使用lxml
解析器,請不要忘記安裝js2py
: pip install js2py
和pip install lxml
。
您可以使用Selenium Webdriver來獲取您感興趣的html內容。 例如,
from selenium import webdriver
def get_html(url):
driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)
time.sleep(5)
html_content = driver.page_source.strip()
return html_content
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.