Python 爬虫小记
User-Agent
ua = UserAgent()
print('ie : ', ua.ie)
print('opera : ', ua.opera)
print('chrome : ', ua.chrome)
print('firefox : ', ua.firefox)
print('safari : ', ua.safari)
for i in range(1, 6):
i += 1
print(ua.random)
headers = {'User-Agent': ua.random}
Host?
定义
Host 请求头指明了请求服务器的域名/IP地址和端口号。
组成:域名+端口号
127.0.0.1:8888
HTTP/1.1 的所有请求报文中必须包含一个 Host 头字段。如果一个 HTTP/1.1 请求缺少 Host 头字段或者设置了超过一个的 Host 头字段,一个400(Bad Request)状态码会被返回
此处盗图一张,需要详细了解Hosts作用,访问王乐平的掘金
Referer or referer
当浏览器向web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器籍此可以获得一些信息用于处理。用于统计访问量、防外连接等
Origin
Origin字段里只包含是谁发起的请求,并没有其他信息。跟Referer不一样的 是Origin字段并没有包含涉及到用户隐私的URL路径和请求内容,这个尤其重要。
并且Origin字段只存在于POST请求,而Referer则存在于所有类型的请求。
代理
proxies = {
"http": "http://10.10.1.10:1000",
"https": "http://10.10.1.10:10001"
}
requests.get("http://xxxx.com", proxies=proxies)
cookie
cookie = {'cookie-key': 'cookie-value'}
resp = = requests.get("http://xxxx.com", cookie=cookie)
s = requests.Session()
# 设置key,value
s.cookies.set('mycookie','value')
# 字典的方式输出
s.cookies.get_dict()
# 更新
ck = requests.cookies.RequestsCookieJar()
ck.set('cookie-name', 'cookie-value')
s.cookies.update(ck)
# 删除指定
s.cookies.set('mycookie',None)
# 删除所有
s.cookies.clear()
# 保存与写入最好将key对应的value转成字符串,否则可能会报错
# 保存到本地文件
#实例化一个LWPcookiejar对象
new_cookie_jar = cookielib.LWPCookieJar('cookie.txt')
#将转换成字典格式的RequestsCookieJar保存到LWPcookiejar中
requests.utils.cookiejar_from_dict({c.name: c.value for c in self.session.cookies}, new_cookie_jar)
#保存到本地文件
new_cookie_jar.save(ignore_discard=True, ignore_expires=True)
# 从本地读取
#实例化一个LWPCookieJar对象
session = requests.session()
load_cookiejar = cookielib.LWPCookieJar()
#从文件中加载cookies(LWP格式)
load_cookiejar.load('cookies.txt', ignore_discard=True, ignore_expires=True)
#工具方法转换成字典
load_cookies = requests.utils.dict_from_cookiejar(load_cookiejar)
#工具方法将字典转换成RequestsCookieJar,赋值给session的cookies.
session.cookies = requests.utils.cookiejar_from_dict(load_cookies)
response
import requests
headers = {
'User-Agent': ua.random,
"Content-Type": "application/json; charset=UTF-8"
}
url = "http://jinbao.pinduoduo.com/network/api/common/goodsList"
pyload = {"keyword": "", "sortType": 0, "withCoupon": 0, "categoryId": 16, "pageNumber": 1, "pageSize": 60}
res = requests.post(url, data=pyload, headers=headers)
print(type(res))
print('res.statue : ', type(res.status_code))
print('headers : ', type(res.headers))
print('text : ', type(res.text))
print('content : ', type(res.content))
print('json : ', type(res.json()))
print('cookies : ', type(res.cookies))
<class 'requests.models.Response'>
res.statue : <class 'int'>
headers : <class 'requests.structures.CaseInsensitiveDict'>
text : <class 'str'>
content : <class 'bytes'>
json : <class 'dict'>
cookies : <class 'requests.cookies.RequestsCookieJar'>
selenium 检测
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
cmd = 'chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\AutomationProfile'
output1 = os.popen(cmd)
res = output1.read()
print(res)
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
chrome_driver = "C:/Program Files (x86)/chromedriver/chromedriver.exe"
browser = webdriver.Chrome(chrome_driver, options=chrome_options)
# 等待iframe完全加载
try:
element = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.ID, "g_iframe")))
except:
print("没有找到相应的iframe")
# 切换到对应的iframe
browser.switch_to.frame("g_iframe")
# 切换回原页面内容
browser.switch_to.default_content()
# cookie
print(browser.get_cookies())
time
# 13 位 unix time
unix_time = int(time.time()*1000)
print(unix_time)
# 转到正常时间
common_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(unix_time/1000))
print(common_time)