首页 > 解决方案 > 使用 beautifulsoup 在 Kickstarter 上抓取多个网址

问题描述

我正在尝试从 kickstarter 网站上获取有关每个项目的每种奖励类别的支持者数量的数据。我的输入是一个网址列表。

我遇到了一些问题:

  1. 我无法从 txt 文件中加载 url,但我的代码仅在列表位于 python 中时才有效。

    我试图抓取的数据示例是这样的(实际上下面有一段我从下面代码中的 2 个链接中抓取的数据):

    ..... ...... , 认捐 500 加元或更多 约 325 欧元 , 认捐 2,500 加元或更多 约 1,625 欧元 , 5 个支持者 , 2 个支持者 ,........ ..

  2. 我需要将上面显示的结果写入每个项目的 CSV 文件的一行中。所以 CSV 文件的第一个单元格将是项目链接(或标题,如果用 beautifulsoup 抓取);第二列应该是一系列值,其中包含每个要约的支持者数量。使用上述数据的示例:

"project link" , "pledge__backer-count" 5 backers , "pledge__amount" $500

我正在努力处理来自 urls 列表的代码部分。第一部分是从网上的一个例子中复制的,效果很好。提前感谢您的帮助,我的论文真的需要这个。"""

from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
import re

def simple_get(url):
    """
    Attempts to get the content at `url` by making an HTTP GET request.
    If the content-type of response is some kind of HTML/XML, return the
    text content, otherwise return None
    """
    try:
        with closing(get(url, stream=True)) as resp:
            if is_good_response(resp):
                return resp.content
            else:
                return None

    except RequestException as e:
        log_error('Error during requests to {0} : {1}'.format(url, str(e)))
        return None

def is_good_response(resp):
    """
    Returns true if the response seems to be HTML, false otherwise
    """
    content_type = resp.headers['Content-Type'].lower()
    return (resp.status_code == 200 
            and content_type is not None 
            and content_type.find('html') > -1)

def log_error(e):
    """
    It is always a good idea to log errors. 
    This function just prints them, but you can
    make it do anything.
    """
    print(e)



urls=['https://www.kickstarter.com/projects/socialismmovie/socialism-an-american-story?ref=home_potd','https://www.kickstarter.com/projects/1653847368/the-cuban-a-film-about-the-power-of-music-over-alz?ref=home_new_and_noteworthy']


for url in urls:
        Project_raw=simple_get(url)
        Project_bs4= BeautifulSoup(Project_raw, 'lxml')

        Backers_offers=Project_bs4.find_all("h2", class_="pledge__amount")
        Backers_per_offer=Project_bs4.find_all("span", class_="pledge__backer-count")
        Offers_plus_Backers=Backers_offers+Backers_per_offer

        print(Offers_plus_Backers)

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


推荐阅读