首页 > 解决方案 > 从 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]) 

但是,连接断开,我收到错误消息。是否有代码可以“跳过”错误的刮擦或类似的东西?

我的“最终目标”是将我的网络历史记录中的关键字分组:

地理位置、性别、年龄等

这是为了看看我们的网络历史代表我们有多准确。
提前致谢

标签: pythonpython-3.x

解决方案


如果有一个特定的错误不断被抛出,你可以使用 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
>>> 

推荐阅读