【问题标题】:Scraping projects urls from Kickstarter using Beautiful Soup使用 Beautiful Soup 从 Kickstarter 抓取项目 url
【发布时间】:2020-03-29 05:33:31
【问题描述】:

我正在尝试使用 Beautiful Soup 从Kickstarter webpage 中抓取项目的 URL。我正在使用以下代码:

import requests
from bs4 import BeautifulSoup

url = 'https://www.kickstarter.com/discover/advanced?category_id=28&staff_picks=1&sort=newest&seed=2639586&page=1'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')

project_name_list = soup.find(class_='grid-row flex flex-wrap')

project_name_list_items = project_name_list.find_all('a')
print(project_name_list_items)

for project_name in project_name_list_items:
    links = project_name.get('href')
    print(links)

但这是我得到的输出:

[<a class="block img-placeholder w100p"><div class="img-placeholder bg-grey-400 absolute t0 w100p"></div></a>, <a class="block img-placeholder w100p"><div class="img-placeholder bg-grey-400 absolute t0 w100p"></div></a>, <a class="block img-placeholder w100p"><div class="img-placeholder bg-grey-400 absolute t0 w100p"></div></a>, <a class="block img-placeholder w100p"><div class="img-placeholder bg-grey-400 absolute t0 w100p"></div></a>, <a class="block img-placeholder w100p"><div class="img-placeholder bg-grey-400 absolute t0 w100p"></div></a>, <a class="block img-placeholder w100p"><div class="img-placeholder bg-grey-400 absolute t0 w100p"></div></a>]
None
None
None
None
None
None

我尝试了几种方法,例如:

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

但仍然没有结果。 此外,我正在抓取的这个页面在页面末尾有一个“加载更多”部分。如何获取该部分的 URL? 感谢您的帮助。

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup


    【解决方案1】:

    数据并未嵌入到 html 本身中,而是以 JSON 形式嵌入到名为 data-project 的 html 属性中。一种解决方案是使用find_all("div") 并仅检查具有该属性的那些

    此外,虽然 url 存在于 JSON 中,但有一个名为 ref 的查询参数存在于另一个名为 data-ref 的 html 属性中。以下获取第 1 页的所有链接

    import requests
    from bs4 import BeautifulSoup
    import json
    
    url = 'https://www.kickstarter.com/discover/advanced?category_id=28&staff_picks=1&sort=newest&seed=2639586&page=1'
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    
    data = [
        (json.loads(i["data-project"]), i["data-ref"])
        for i in soup.find_all("div")
        if i.get("data-project")
    ]
    
    for i in data:
        print(f'{i[0]["urls"]["web"]["project"]}?ref={i[1]}')
    

    然后您可以通过增加page 查询参数来迭代页面(“加载更多”按钮)

    【讨论】:

    猜你喜欢
    • 2017-03-30
    • 2018-07-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2023-03-31
    • 1970-01-01
    • 2022-08-22
    相关资源
    最近更新 更多