python - 从 csv 文件中抓取多个 url
问题描述
我目前有以下代码:
from bs4 import BeautifulSoup
import requests
import csv
with open("safari history.csv") as f_urls, open("Titles.txt", "w", newline="") as f_output:
csv_output = csv.writer(f_output)
csv_output.writerow(['Title'])
for url in f_urls:
#url = url.strip()
#t = lxml.html.parse(url)
response = requests.get(url)
soup = BeautifulSoup(response.text, "lxml")
titles = soup.find_all('meta')
print( [meta.attrs['content']for meta in titles if 'name' in meta.attrs and meta.attrs['name'] == 'description'])
csv_output.writerow([titles])
但是,连接断开,我收到错误消息。是否有代码可以“跳过”错误的刮擦或类似的东西?
我的“最终目标”是将我的网络历史记录中的关键字分组:
地理位置、性别、年龄等
这是为了看看我们的网络历史代表我们有多准确。
提前致谢
解决方案
如果有一个特定的错误不断被抛出,你可以使用 try/except 块来处理成功并简单地传递错误:
try:
do_work(url)
except YourExceptionType:
#Do nothing
pass
来自外壳的小例子:
>>> float("not a float")
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
float("not a float")
ValueError: could not convert string to float: 'not a float'
>>> s = "not a float"
>>> try:
print(float(s))
except ValueError:
print("Exception caught")
Exception caught
>>>
推荐阅读
- python - 我如何使用 Numpy 计算我的数组中有多少条目,例如给出 0,9 的累积总和?
- java - Xodus Java:找不到符号 PersistentEntityStores
- python - 使用python查找带有if条件的字符串
- azure - Microsoft Azure 人脸 API - 使用 Node-RED 进行人脸检测
- ocr - 在 windows 上训练 tesseract4.0 的过程
- css - 在 wordpress 模板中插入一行文本,仅在主页和按钮下方
- python - python中的Cutout2D
- ruby-on-rails - HTTP::Client Gem 的未定义方法“prepend”
- java - 用 Selenium 上传文件?
- c# - 如何在 Blazor 中本地化身份?