[英]Scraping multiple pages with bs4 Beautiful Soup - only scrapes the first page
[英]Web scraping with BeautifulSoup only scrapes the first page
我正在嘗試從 webmd 留言板中抓取一些數據。 最初我構建了一個循環來獲取每個類別的頁碼並將其存儲在數據框中。 當我嘗試運行循環時,我確實為每個子類別獲得了適當數量的帖子,但僅限於第一頁。 任何想法可能會出錯?
lists2=[]
df1= pd.DataFrame (columns=['page'],data=page_links)
for j in range(len(df1)):
pages = (df1.page.iloc[j])
print(pages)
req1 = urllib.request.Request(pages, headers=headers)
resp1 = urllib.request.urlopen(req1)
soup1 = bs.BeautifulSoup(resp1,'lxml')
for body_links in soup1.find_all('div',class_="thread-detail"):
body= body_links.a.get('href')
lists2.append(body)
我在打印功能中獲得了正確的頁面,但它似乎只在第一頁中迭代並獲取帖子的鏈接。 此外,當我復制並粘貼除第一個頁面之外的任何頁面的鏈接時,它似乎會暫時加載第一頁,然后轉到正確的編號頁面。 我試圖添加time.sleep(1)
但不起作用。 我嘗試的另一件事是添加{headers='Cookie': 'PHPSESSID=notimportant'}
替換這一行:
pages = (df1.page.iloc[j])
有了這個:
pages = (df1.page.iloc[j, 0])
您現在將遍歷 DataFrame 的值
如果page_links
是帶有 url 的列表,例如
page_links = ["http://...", "http://...", "http://...", ]
那么你可以直接使用它
for url in page_links:
req1 = urllib.request.Request(url headers=headers)
如果您在 DataFrame 中需要它,那么
for url in df1['page']:
req1 = urllib.request.Request(url headers=headers)
但是,如果您當前的代碼顯示所有 url,但您只得到一頁的結果,那么問題不在DataFrame
而在HTML
和find_all
。
似乎只有第一頁有<div class_="thread-detail">
所以它在其他頁面上找不到它,也不能將它添加到列表中。 你應該再檢查一次。 對於其他頁面,您可能需要在find_all
不同的參數。 但是如果沒有這些頁面的 url,我們就無法檢查它,也無法提供更多幫助。
這可能是其他常見問題 - 頁面可能使用JavaScript
添加這些元素,但BeautifulSoup
無法運行JavaScript - and then you woould need [Selenium](https://selenium-python.readthedocs.io/) to control web browser which can run JavaScript. You could turn off JavaScript in browser and open urls to check if you can see elements on page and in HTML in
JavaScript - and then you woould need [Selenium](https://selenium-python.readthedocs.io/) to control web browser which can run JavaScript. You could turn off JavaScript in browser and open urls to check if you can see elements on page and in HTML in
在 Chrome/Firefox JavaScript - and then you woould need [Selenium](https://selenium-python.readthedocs.io/) to control web browser which can run JavaScript. You could turn off JavaScript in browser and open urls to check if you can see elements on page and in HTML in
DevTools` 中JavaScript - and then you woould need [Selenium](https://selenium-python.readthedocs.io/) to control web browser which can run JavaScript. You could turn off JavaScript in browser and open urls to check if you can see elements on page and in HTML in
元素。
至於帶有requests
PHPSESSID
,您可以使用Session
從服務器獲取帶有PHPSESSID
新鮮 cookie,並自動將它們添加到其他請求中
import requests
s = reqeusts.Session()
# get any page to get fresh cookies from server
r = s.get('http://your-domain/main-page.html')
# use it automatically with cookies
for url in page_links:
r = s.get(url)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.