从csv fi中刮取多个URL

2024-04-19 18:54:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前拥有以下代码:

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]) 

但是,连接断开,我得到一个错误。有没有代码可以“跳过”一个错误的刮擦,或者类似的东西

我的“最终目标”是将我的网络历史中的关键字分为以下几类:

geographical location, gender, age, etc.

这是为了看看我们的网络历史如何准确地代表我们。
提前谢谢


Tags: csv代码inimporturloutputasopen
1条回答
网友
1楼 · 发布于 2024-04-19 18:54:01

如果有一个特定的错误不断被抛出,您可以使用try/except块来处理一个成功并简单地传递错误:

try:
    do_work(url)
except YourExceptionType:
    #Do nothing
    pass

来自shell的小示例:

>>> 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
>>> 

相关问题 更多 >