簡體   English   中英

使用美麗的湯從未知頁數中抓取數據

[英]scraping data from unknown number of pages using beautiful soup

我想從網站解析一些信息,這些信息的數據分布在幾個頁面中。

問題是我不知道有多少頁面。 可能有2個,但也可能有4個,甚至只有一個頁面。

當我不知道會有多少頁面時,我怎么能遍歷頁面?

我知道url模式看起來像下面的代碼。

此外,網頁名稱不是普通的數字,但他們在'pe2' 2頁和'pe4' 3頁等,所以不能隨便超范圍(數)循環。

這個我正在嘗試修復的循環的虛擬代碼。

pages=['','pe2', 'pe4', 'pe6', 'pe8',]

import requests 
from bs4 import BeautifulSoup
for i in pages:
    url = "http://www.website.com/somecode/dummy?page={}".format(i)
    r = requests.get(url)
    soup = BeautifulSoup(r.content)
    #rest of the scraping code

您可以使用while循環,它會在遇到異常時停止運行。

碼:

from bs4 import BeautifulSoup
from time import sleep
import requests 

i = 0
while(True):
    try:
        if i == 0:
            url = "http://www.website.com/somecode/dummy?page=pe"
        else:
            url = "http://www.website.com/somecode/dummy?page=pe{}".format(i)
        r = requests.get(url)
        soup = BeautifulSoup(r.content, 'html.parser')

        #print page url
        print(url)

        #rest of the scraping code

        #don't overflow website
        sleep(2)

        #increase page number
        i += 2
    except:
        break

輸出:

http://www.website.com/somecode/dummy?page
http://www.website.com/somecode/dummy?page=pe2
http://www.website.com/somecode/dummy?page=pe4
http://www.website.com/somecode/dummy?page=pe6
http://www.website.com/somecode/dummy?page=pe8
...
... and so on, until it faces an Exception.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM