【发布时间】:2020-06-09 11:56:21
【问题描述】:
除了末尾的数字外,我正在使用相同的 url 遍历多个页面。但是,一旦它达到 404,它就会冻结程序,即使我在 try 块中捕获了异常。我在这里错过了什么吗?这是我的代码。程序一旦点击https://www.tenable.com/plugins/nessus/14587就会挂起
import bs4 as bs
from urllib.request import urlopen, Request
import urllib
ID = 14580
while ID < 132734:
#ID == 14391
ID == 14580
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'}
reg_url = "https://www.tenable.com/plugins/nessus/" + str(ID)
req = Request(url=reg_url, headers=headers)
try:
source = urlopen(req).read()
except urllib.error.HTTPError as e:
if e.getcode() == 404: # check the return code
continue
raise
soup = bs.BeautifulSoup(source,'lxml')
print(ID)
print(reg_url)
print(soup.title.string)
ID += 1
更新的工作代码:
import bs4 as bs
from urllib.request import urlopen, Request
import urllib
ID = 14580
while ID < 132734:
#ID == 14391
ID == 14580
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'}
reg_url = "https://www.tenable.com/plugins/nessus/" + str(ID)
req = Request(url=reg_url, headers=headers)
try:
source = urlopen(req).read()
except urllib.error.HTTPError as e:
if e.getcode() == 404: # check the return code
ID +=1
continue
raise
soup = bs.BeautifulSoup(source,'lxml')
print(ID)
print(reg_url)
print(soup.title.string)
ID += 1
【问题讨论】:
-
continue阻止了ID += 1被执行,所以你的 ID 卡在了 14587。 -
@JoachimLusiardi 啊,我错过了,谢谢。关于在保持 try catch 块的同时不断增加 ID 的好方法有什么想法吗?
-
我在异常块内向 ID 添加了另一个增量,现在它工作正常
-
好的 :) 很高兴为您提供帮助
标签: python web-scraping beautifulsoup http-status-code-404 urllib