Python 几种爬虫的方法

Python 几种爬虫的方法

一、使用Requests库

1.1安装Requests库

pip install Requests

1.2实例:

import Requests

r = Requests.get(url)

print r.text

print  r.status_code

传递URL参数

import requests

key_dict = {'key1':'value1','key2':'value2'}

r = requests.get(url,params=key_dict)

定制请求头

import requests

headers = {"User-Agent":......,

"Host":......}

r = requests.get(url,headers=headers)

print (“响应状态码:”,r.status_code)

二、使用selenium模拟浏览器

2.1安装selenium

pip install selenium

示例:

from selenium import webdriver

driver = webdriver.Firefox()

driver.get(url)

注:使用selenium模拟浏览器时,需要下载对应的驱动,例如:火狐:需要下载geckodriver.exe;谷歌:需要下载chromdriver.exe;IE:需要下载IEDriverServer.exe ;下载好驱动后,放在相应的浏览器安装目录下,并将其加入环境变量

遇到的问题:

1.Python2和3中'ascii' codec can't decode position 0: ordinal not in range(128)

python2:

在开头加上
import sys 

reload(sys)

sys.setdefaultencoding('utf-8')

python3:

x = pickle.load(open("./data/coco/word2vec.p","rb"),encoding='bytes')

2.使用demjson

pip install demjson

demjson.encode --将对象转换json

demjsonl.decode --将json转化为对象

3.print ()

使用

i = cool

print("中文测试:" + i )

使用上述方法容易乱码

可以使用:

print (“中文测试 %s”) % i

解决

猜你喜欢

转载自www.cnblogs.com/xuyiwen/p/10522203.html