gpt4 book ai didi

python - 继续基于错误的 Python 脚本

转载 作者:行者123 更新时间:2023-12-01 03:24:46 25 4
gpt4 key购买 nike

我在 Ubuntu 14.04 上使用 python 2.7 通过旋转代理进行抓取...抓取错误几分钟后:

raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', BadStatusLine("''",))


if keyword1 in text and keyword2 in text and keyword3 in text:
print("LINK SCRAPED")
print(text, "link scraped")
found = True
break

except requests.exceptions.ConnectionError as err:
print("Encountered ConnectionError, retrying: {}".format(err))

如果这不是实现 try 的正确方法,我假设只有 request 进入 try 子句,其他所有内容都在 except 之后?

最佳答案

您可以使用 try/except 语句来处理错误,而不是重新启动脚本。

例如:

try:
# line of code that is failing
except requests.exceptions.ConnectionError as err:
print("Encountered ConnectionError, retrying: {}".format(err))

然后重试原始调用。

更新:根据您更新的代码示例,我将执行以下操作:

from bs4 import BeautifulSoup
import requests
import smtplib
import urllib2
from random import randint
import time
from lxml import etree
from time import sleep
import random


proxies = {'https': '100.00.00.000:00000'}
hdr1 = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive',
}

hdrs = [hdr1] #, hdr2, hdr3, hdr4, hdr5, hdr6, hdr7]
ua = random.choice(hdrs)
head = {
'Connection': 'close',
'User-Agent': ua,
}

##### REQUEST 1 ####
done = False
while not done:
try:
a = requests.get('https://store.fabspy.com/sitemap.xml', proxies=proxies, headers=head)
done = True
except requests.exceptions.ConnectionError as err:
print('Encountered ConnectionError, retrying: {}'.format(err))
time.sleep(1)

scrape = BeautifulSoup(a.text, 'lxml')
links = scrape.find_all('loc')
for link in links:
if 'products' in link.text:
sitemap = str(link.text)
break

keyword1 = 'not'
keyword2 = 'on'
keyword3 = 'site'

######### REQUEST 2 #########
done = False
while not done:
try:
r = requests.get(sitemap, proxies=proxies, headers=head)
done = True
except requests.exceptions.ConnectionError as err:
print('Encountered ConnectionError, retrying: {}'.format(err))
sleep(randint(4,6))

soup = BeautifulSoup(r.text, 'lxml')
links = soup.find_all('loc')
for link in links:
text = link.text
if keyword1 in text and keyword2 in text and keyword3 in text:
print(text, 'link scraped')
break

关于python - 继续基于错误的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498102/

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