首页 > 解决方案 > 抓取“下一页”BeautifulSoup 或 Scrapy?

问题描述

我正在做我的第一个真正的项目。我正在尝试从rotoworld 的新闻提要中抓取所有 nfl 球员新闻:

我已经成功地使用 BeautifulSoup 中的 bs4 从第一页中提取了我想要的所有信息,但我正在研究如何从“旧”选项卡中访问信息。我认为如果每次打开新页面时 url 都会更改,那么执行此操作会很容易,但事实并非如此。我想知道是否有人对使用 BS 抓取“下一页”有任何提示,或者我是否应该尝试像 scrappy 这样的程序?

我正在使用 python 3。这是我为感兴趣的人准备的代码。

    from urllib.request import urlopen as uReq
    from bs4 import BeautifulSoup as soup

    my_url="http://www.rotoworld.com/playernews/nfl/football/"

    # opening up connection, grabing the page 
    uClient = uReq(my_url)
    page_html = uClient.read()
    uClient.close()

    #html parsing
    page_soup = soup(page_html, "html.parser")

    #grabs each news report

    containers = page_soup.findAll("div",{"class":"pb"})

    filename = "nfl_player_news.csv"
    f = open(filename, "w")

    headers = "Player, Position, Team, Report, More Info, date\n"

    f.write("")

    for container in containers:
        ugly_player_info = container.div.div.text.strip("\r\n")
        neat_player_info = " ".join(ugly_player_info.split())
        player = container.div.div.a.text
        position = " ".join(neat_player_info.split()[3:4])
        team = " ".join(neat_player_info.split()[5:])

        report = container.p.text.strip()

        more_info = container.findAll("div",{"class":"impact"})
        info = more_info[0].text.strip()

        date_messy = container.findAll("div",{"class":"date"})
        date_time = date_messy[0].text.strip()
        ny_date= " ".join(date_time.split()[0:2])
        date = ny_date + " 2018"

        print("player" + player) 
        print("position" + position) 
        print("team" + team) 
        print("report" + report) 
        print("info" + info) 
        print("date" + date) 

        f.write(player + "," + position + "," + team + "," + report.replace(",", "|") + "," + info.replace(",","|") + "," + date + "\n")

    f.close()

标签: loopsweb-scrapingbeautifulsoup

解决方案


通常,对于此类问题,您希望查看两个替代方案之一。

  1. 使用Selenium打开页面并每次单击“旧”按钮并获取新页面。
  2. 检查页面并转到网络选项卡。现在单击“较旧”按钮,您将 - 在您的情况下 - 在响应中以 html 形式返回较旧页面的 post 调用。然后你可以解析它。

此外,您可以使用 Scrapy 预先获取大量此类样板代码并加快开发速度。


推荐阅读