繁体   English   中英

使用 BeautifulSoup 进行抓取移动到下一页

[英]Moving to the next page using BeautifulSoup for scraping

我需要从网站上抓取内容(只是标题)。 我只做了一页,但我需要对网站上的所有页面都做。 目前,我的做法如下:

import bs4, requests
import pandas as pd
import re

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
    
    
r = requests.get(website, headers=headers)
soup = bs4.BeautifulSoup(r.text, 'html')


title=soup.find_all('h2')

我知道,当我移动到下一页时,url 更改如下:

website/page/2/
website/page/3/
... 
website/page/49/
...

我尝试使用 next_page_url = base_url + next_page_partial 构建递归函数,但它没有移动到下一页。

if soup.find("span", text=re.compile("Next")):
    page = "https://catania.liveuniversity.it/notizie-catania-cronaca/cronacacatenesesicilina/page/".format(page_num)
    page_num +=10 # I should scrape all the pages so maybe this number should be changed as I do not know at the beginning how many pages there are for that section
    print(page_num)
else:
    break

我关注了这个问题(和答案): 移动到下一页使用 BeautifulSoup 进行抓取

如果您需要更多信息,请告诉我。 非常感谢

更新代码:

import bs4, requests
import pandas as pd
import re

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}

page_num=1
website="https://catania.liveuniversity.it/notizie-catania-cronaca/cronacacatenesesicilina"

while True:
  r = requests.get(website, headers=headers)
  soup = bs4.BeautifulSoup(r.text, 'html')


  title=soup.find_all('h2')

  if soup.find("span", text=re.compile("Next")):
      page = f"https://catania.liveuniversity.it/notizie-catania-cronaca/cronacacatenesesicilina/page/{page_num}".format(page_num)
      page_num +=10
  else:
      break

如果您使用f"url/{page_num}"则删除format(page_num)

您可以在下面使用任何您想要的东西:

page = f"https://catania.liveuniversity.it/notizie-catania-cronaca/cronacacatenesesicilina/page/{page_num}"

或者

page = "https://catania.liveuniversity.it/notizie-catania-cronaca/cronacacatenesesicilina/page/{}".format(page_num)

祝你好运!


最终答案将是这样的:

import bs4, requests
import pandas as pd
import re

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}

page_num=1
website="https://catania.liveuniversity.it/notizie-catania-cronaca/cronacacatenesesicilina"

while True:
  r = requests.get(website, headers=headers)
  soup = bs4.BeautifulSoup(r.text, 'html')


  title=soup.find_all('h2')

  if soup.find("span", text=re.compile("Next")):
      website = f"https://catania.liveuniversity.it/notizie-catania-cronaca/cronacacatenesesicilina/page/{page_num}"
      page_num +=1
  else:
      break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM