爬虫

#-*- coding:utf-8 -*-
import urllib, urllib2
import time
from fake_useragent import UserAgent
import requests
import threading
from bs4 import BeautifulSoup
def get_page_source( url):
headers = { 'User-Agent': UserAgent().random}
req = urllib2.Request(url, None, headers=headers)
response = urllib2.urlopen(req)
page_source = response.read()
return page_source
count= 0
filename= 'IpPool.txt'
for i in range( 1, 3):
url= "http://www.xicidaili.com/nn/ %s "%i
html=get_page_source(url)
soup=BeautifulSoup(html, 'html5lib')
list = []
for idx, tr in enumerate(soup.find_all( 'tr')):
if idx != 0:
tds = tr.find_all( 'td')
ip=tds[ 1].contents[ 0]
port=tds[ 2].contents[ 0]
ipt=ip+ ':'+port
list.append(ipt)
lock=threading.Lock() #建立一个锁
def test( i):
global lock,count
lock.acquire()
count=count+ 1
proxy={ 'http':i}
url= "https://www.baidu.com"
resp=requests.get(url, proxies=proxy)
if resp.status_code== 200:
# print(i), #python2不换行
with open(filename, 'a') as f:
f.write(i+ ' \n ')
f.close()
print( " %s : %s %s "%(count,i,resp.status_code))
lock.release()
threads=[]
for i in list:
thread=threading.Thread( target=test, args=(i,))
threads.append(thread)
thread.start()
#阻塞主进程,等待所有子线程结束
for thread in threads:
thread.join()



import requests
from fake_useragent import UserAgent
ua = UserAgent()
headers = { 'User-Agent': ua.random}
url = 'http://www.xicidaili.com/nn/1'
resp = requests.get(url, headers=headers)
print(resp.text)
print(resp.encoding) #获得编码
print(resp.text.encode( 'utf-8')) #去编码
print(resp.status_code) #返回表示码

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值