gpt4 book ai didi

python - 从多个网站提取文本

转载 作者:太空宇宙 更新时间:2023-11-03 21:47:50 27 4
gpt4 key购买 nike

from bs4 import BeautifulSoup
import re
import urllib2
import urllib
list_open = open("weblist.txt")
read_list = list_open.read()
line_in_list = read_list.split("\n")
for url in line_in_list:
Beautiful = urllib2.urlopen(url).read()
beautiful
soup = bs4.BeautifulSoup(beautiful)
for news in soup:
print soup.getText()

以下代码帮助我从多个网站(weblist.txt)提取文本

但是,当我的网络列表包含任何无法使用此代码打开的链接或网站时,它会立即停止,并且不会检查其他链接。假设如果我有 10 个链接,第二个链接未打开或无法解析,它会给出错误并停止在该链接中,而不检查进一步的链接。我希望它应该检查网络列表中的每个链接(从开始到结束)并从中提取文本所有这些链接都是真实的或能够解析的。

最佳答案

只需添加一个 try except 语句,如下所示:

for url in line_in_list:
try:
Beautiful = urllib2.urlopen(url).read()
beautiful
soup = bs4.BeautifulSoup(beautiful)
for news in soup:
print soup.getText()
except Exception as e:
#Error handling
print(e)

关于python - 从多个网站提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52351025/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com