python - 使用 beautifulsoup 在 Kickstarter 上抓取多个网址
问题描述
我正在尝试从 kickstarter 网站上获取有关每个项目的每种奖励类别的支持者数量的数据。我的输入是一个网址列表。
我遇到了一些问题:
我无法从 txt 文件中加载 url,但我的代码仅在列表位于 python 中时才有效。
我试图抓取的数据示例是这样的(实际上下面有一段我从下面代码中的 2 个链接中抓取的数据):
..... ...... , 认捐 500 加元或更多 约 325 欧元 , 认捐 2,500 加元或更多 约 1,625 欧元 , 5 个支持者 , 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)
解决方案
推荐阅读
- mysql - 使用的 SELECT 语句在 codeigniter 中有不同数量的列
- css - Mediawiki:我需要提示如何调试»遇到的异常,类型为“ParseError”«
- c++ - 如何防止 googletest 从我的测试代码中吞下 stdout (std::cout)?
- python - 将一个df的一列连接到另一个df的所有列
- powershell - 仅在文本文件中从第 5 列中删除空格
- git - 如何从本地 git 服务器克隆特定的 Git 分支
- watchkit - iwatch 并发症未在表盘并发症列表中列出,但出现在 iphone 的并发症部分
- javascript - 如何使情况真实 JAVASCRIPT
- c++ - 使用 Xlib 获取应用程序的图标?
- ios - 我可以阻止删除 ios mdm 配置文件吗?