一、使用代理IP池,利用代理IP进行爬取数据(免费的IP太难找了,示例代码中还应补充如果IP不能用,可以提示用户替换,由于用不到所以没有添加。仅供参考)
二、设置浏览器信息
三、设置连接网站动态访问时间
一、使用代理IP池,利用代理IP进行爬取数据(示例代码)
#使用代理IP池
def dynamic_IP ():
http_ip = ['222.242.106.7:80','11.11.11.11:80'] #使用的代理IP
proxy_ip = {'http': random.choice(http_ip)} # choice() 方法返回一个列表,元组或字符串的随机项。
url = "http://www.ip111.cn/"
html = requests.get(url=url)
soup = BeautifulSoup(html.text, 'lxml')
print('本机IP:', soup.find_all('p')[0].text)
print(proxy_ip)
try:
html2 = requests.get(url=url, proxies=proxy_ip)
code = html2.status_code
soup = BeautifulSoup(html2.text, 'lxml')
print('代理IP,可以使用:', soup.find_all("p")[0].text)
global proxy_ip2
proxy_ip2=proxy_ip
except:
print('代理IP不可以用')
'''
使用代码200进行判断,但有一些网站可以成功链接,也有200标示,但没有可用信息
code = html2.status_code
print(code)
if code == 200:
print("OK 网站访问正常")
else:
'''
二、设置浏览器信息(示例代码)
headers = {"Accept": "text/html,application/xhtml+xml,application/xml;",
"Accept-Encoding": "gzip",
"Accept-Language": "zh-CN,zh;q=0.8",
"Referer": "http://permit.mee.gov.cn/",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
}
datas = {"registerentername": "",
"xkznum": "",
"treadname": "",
"treadcode": "",
"publishtime": ""}
url ="www.baidu.com"
r = requests.post(url,data=datas,headers=headers)#如果使用代理服务器就添加proxies=proxy_ip2
html = etree.HTML(r.text)
三、设置连接网站动态访问时间(示例代码 )
time_random = [1.5,0.5,0.6,2,3,4,1] #时间单位为秒,数据与数量任意设置
time_test = random.choice(time_random)#随机读取列表中数据,做为暂停秒数
time.sleep(time_test)
print('延迟时间:', time_test)
联合使用示例代码
def dynamic_IP (): #............................................代理IP获取及验证
http_ip = [
'222.242.106.7:80' ,
'11.11.11.11:80'
]
proxy_ip = {
'http': random.choice(http_ip), # choice() 方法返回一个列表,元组或字符串的随机项。
}
url = "http://www.ip111.cn/"
html = requests.get(url=url)
soup = BeautifulSoup(html.text, 'lxml')
print('本机IP:', soup.find_all('p')[0].text)
print(proxy_ip)
try:
html2 = requests.get(url=url, proxies=proxy_ip)
code = html2.status_code
soup = BeautifulSoup(html2.text, 'lxml')
print('代理IP,可以使用:', soup.find_all("p")[0].text)
global proxy_ip2
proxy_ip2=proxy_ip
except:
print('代理IP不可以用')
def kaishipaqu_begin():
dynamic_IP ()
headers = {"Accept": "text/html,application/xhtml+xml,application/xml;",
"Accept-Encoding": "gzip",
"Accept-Language": "zh-CN,zh;q=0.8",
"Referer": "http://www.baidu.com/",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
}
datas = {"registerentername": "",
"xkznum": "",
"treadname": "",
"treadcode": "",
"publishtime": ""}
url ="www.baidu.com"
time_random = [1.5,0.5,0.6,2,3,4,1] #时间单位为秒,数据与数量任意设置
time_test = random.choice(time_random)#随机读取列表中数据,做为暂停秒数
time.sleep(time_test)
print('延迟时间:', time_test)
r = requests.post(url,data=datas,headers=headers,proxies=proxy_ip2)
html = etree.HTML(r.text)