【问题标题】:Get all links with BeautifulSoup from a single page website ('Load More' feature)从单页网站获取所有带有 BeautifulSoup 的链接(“加载更多”功能)
【发布时间】:2016-06-21 07:58:55
【问题描述】:

我想从没有分页的网站上抓取所有链接,即有一个“加载更多”按钮,但 URL 不会根据您要求的数据量而改变。

当我BeautifulSoup 页面并请求所有链接时,它只是显示网站原始首页上的链接数量。我可以通过单击“加载更多”按钮手动单击旧内容,但有没有办法以编程方式执行此操作?

这就是我的意思:

page = urllib2.urlopen('http://www.thedailybeast.com/politics.html')
soup = soup = BeautifulSoup(page)

for link in soup.find_all('a'):
    print link.get('href')

不幸的是,没有负责分页的 URL。

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    当您单击“加载更多”按钮时,会向http://www.thedailybeast.com/politics.view.<page_number>.json 端点发出XHR 请求。您需要在代码中模拟它并解析 JSON 响应。使用requests 的工作示例:

    import requests
    
    with requests.Session() as session:
        for page in range(1, 10):
            print("Page number #%s" % page)
            response = session.get("http://www.thedailybeast.com/politics.view.%s.json" % page)
            data = response.json()
    
            for article in data["stream"]:
                print(article["title"])
    

    打印:

    Page number #1
    The Two Americas Behind Donald Trump and Bernie Sanders
    ...
    Hillary Clinton’s Star-Studded NYC Bash: Katy Perry, Jamie Foxx, and More Toast the Candidate
    Why Do These Republicans Hate Maya Angelou’s Post Office?
    Page number #2
    No, Joe Biden Is Not a Supreme Court Hypocrite
    PC Hysteria Claims Another Professor
    WHY BLACK CELEB ENDORSEMENTS MATTER MOST
    ...
    Inside Trump’s Make Believe Presidential Addresses
    ...
    

    【讨论】:

    • 谢谢,很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 2019-09-07
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    相关资源
    最近更新 更多