【发布时间】:2018-07-10 05:29:44
【问题描述】:
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
import re
import csv
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# text = input ('Enter Text - ') - In-case the user wants to manually put-in
some text to evaluate
#print ('\n')
#print (len(lst))
# Take 'Content' input from a csv file
file = open("Test_1.CSV", "r", encoding='utf-8')
reader = csv.reader(file)
for line in reader:
text = line[5]
lst = re.findall('(http.?://[^\s]+)', text)
if not lst: print(line[0], 'Empty List')
else:
try:
for url in lst:
try:
try:
html = urllib.request.urlopen(url, context=ctx).read()
#html = urllib.request.urlopen(urllib.parse.quote(url, errors='ignore'), context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
title = soup.title.string
str_title = str (title)
if 'Twitter' in str_title:
if len(lst) > 1: break
else: continue
else:
print (line[0], str_title, ',', url)
except UnicodeEncodeError as e:
#print("Incorrect URL {}".format(url.encode('ascii', errors='ignore')))
b_url = url.encode('ascii', errors='ignore')
n_url = b_url.decode("utf-8")
#print (n_url)
html = urllib.request.urlopen(n_url, context=ctx).read()
#html = urllib.request.urlopen(urllib.parse.quote(url, errors='ignore'), context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
title = soup.title.string
str_title = str (title)
if 'Twitter' in str_title:
if len(lst) > 1: break
else: continue
else:
print (line[0], str_title, ',', url)
except urllib.error.URLError:
print ('Invalid DNS Link')
except urllib.error.HTTPError as err:
if err.code == 404:
print (line[0], 'Invalid Twitter Link')
上述代码读取一个 csv 文件,选择一列,然后使用正则表达式解析该文件以获取单行中的所有超链接,然后我使用 BeautifulSoup 解析超链接以获取页面的“标题字符串” .
在运行这段代码时,我首先遇到了UnicodeEncodeError 并解决了它;然后我遇到了urllib.error.URLError 并解决了这个问题。现在,我又遇到了一个
"Traceback (most recent call last): File "C:\Users\asaxena\Desktop\py4e\Gartner\crawler_new.py", line 32, in <modu le> title = soup.title.string AttributeError: 'NoneType' object has no attribute 'string'".
我真的有办法绕过出现的任何类型的错误吗?甚至那些不可预见的?我知道 BeautifulSoup 倾向于抛出意外错误,部分原因是网络上漫游的内容种类繁多。
【问题讨论】:
-
你的问题太宽泛了。您想绕过任何类型的错误吗?使用 try except exception,它将捕获所有异常,但这始终是一种不好的做法。
-
尝试更改变量标题的名称
-
我面临的问题是,我的代码每次遇到错误时都会中断,如果记录错误,我可以“继续”吗?你能帮我修复代码吗?
-
Title 变量是否会导致任何不可预见的问题?
-
遗憾的是,这两种方法似乎都不适合我。
标签: python python-3.x beautifulsoup urllib