最近用python做腳本的時(shí)候,發(fā)現(xiàn)了一個(gè)問題,就是獲取的網(wǎng)頁并不全??赡茉蛑皇琼撁鎯?nèi)容過大,無法加載全部到內(nèi)存中
下面的解決方法只針對(duì)靜態(tài)加載頁面(有的網(wǎng)頁是動(dòng)態(tài)加載數(shù)據(jù),需要查看對(duì)應(yīng)的js請(qǐng)求或者用selenium來獲取就好)。
解決方法為放入文件里,再讀取即可
使用selenium,代碼如下
browser = webdriver.Chrome(service=webdriver_service, options=option)
browser.get(url)
browser.implicitly_wait(10) # 等待頁面加載完畢,最多等待10s
# print(browser.page_source)
# str(browser.page_source)
soup = BeautifulSoup(browser.page_source,"lxml")
soup.find(xxxx)
soup.find(xxxx) 獲取不到,但是在網(wǎng)頁上F12查找元素是有的。于是查看network,但是并未發(fā)現(xiàn)有ajax異步數(shù)據(jù),只有靜態(tài)數(shù)據(jù),于是打印頁面源碼,print(browser.page_source),發(fā)現(xiàn)獲取的 html 頁面內(nèi)容并不全,并且每次獲取的html 內(nèi)容不一樣,每次都是獲取到一半就沒有了。轉(zhuǎn)成str打印也是一樣的效果。于是懷疑是selenium的問題,又換用requests
source_html = requests.get(url)
soup = BeautifulSoup(browser.source_html,"lxml")
soup.find(xxxx)
還是一樣的效果,還是找不到。
以為是頁面沒加載完畢,sleep(3) 睡眠3s依舊不行
搜索后終于在一個(gè)博客找到些線索,于是用下列方式,問題就解決了.
把獲取到的頁面內(nèi)容保存到文件里,再讀取,就拿到了??赡茉蚴琼撁孢^大,python的輸出限制長度。
tmp_html = "temp.html"
source_html = requests.get(url)
with open(tmp_html, "w+", encoding="utf-8") as f:
f.write(source_html.text)
f.seek(0)
html_handle = f.read()
soup = BeautifulSoup(html_handle,"lxml")
soup.find(xxxx)
如果文件過大無法寫入,可使用requests.iter_content寫
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
這次soup.find(xxxx)找到了,并且文件里也是完整的html內(nèi)容。
如果文件過大,soup = BeautifulSoup(html_handle,“l(fā)xml”) Beautifulsoup無法加載,可以使用使用SAX解析器文章來源:http://www.zghlxwxcb.cn/news/detail-824322.html
參考鏈接
requests.get()獲取信息不完整
使用BeautifulSoup加載大型xml文件文章來源地址http://www.zghlxwxcb.cn/news/detail-824322.html
到了這里,關(guān)于requests或selenium獲取網(wǎng)頁內(nèi)容不全問題(非異步加載)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!