【发布时间】:2018-04-13 23:38:52
【问题描述】:
我正在构建一个网络爬虫,但遇到了障碍。基本上,爬虫会找到 的所有值,然后尝试系统地导航到所有这些相关链接。例如,如果在http://example.com 的主页上有“home.html”和“about.html”链接,爬虫将通过并尝试请求基本域+新找到的域(例如http://example.com/home.html, http://example.com/about.html)。
但是,在我的测试站点上,我将其设置在 的位置。当 python 中的 urllib 函数尝试请求 .pdf 文件时,我收到此错误:
有没有一种方法可以构建一个 try / 除非发生这种情况时忽略 URL?这是我目前拥有的相关代码:
def soupify(url):
"""
:param: URL string.
:return: HTML BeautifulSoup object as html.parser
Process: Requests website for HTML code. If it responds, converts the code into IO stream so that it can become a
Soup object.
"""
# Header info so that the web server does not deny the request
hdr = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'}
req = urllib.request.Request(url, headers=hdr)
page = urllib.request.urlopen(req)
# This is to create in memory the HTML code of the page.
file = io.TextIOWrapper(page, encoding='utf-8')
fileContents = file.read()
soupObject = soup(fileContents, "html.parser")
return soupObject
然后,当我尝试实际访问 URL 后,会发生什么情况。
url = baseDomain + queue[0]
queueLength = len(queue)
print("Queue:", queueLength)
isError = False
# Exception handling when attempting to make a soup object.
try: fileContents = soupify(url)
except urllib.error.HTTPError: # If the website returns an HTTP error, such as a 404
inaccessibleSites += 1
isError = True
queue.pop(0)
except urllib.error.URLError: # If the website does not exist or does not have a valid URL
inaccessibleSites += 1
isError = True
queue.pop(0)
# Here is where I want to build an except to handle the bad codec but I am not sure where to start
代码继续运行,但这是导致错误的主要部分。有任何想法吗?我想这很容易解决。
【问题讨论】:
-
请将您的回溯发布为文本,而不是屏幕截图。
标签: python beautifulsoup web-crawler urllib