Python crawler common code

table of Contents

Python crawler common code

Web foundation:

Request core code:

POST related:

BeautifulSoup:


 

Web foundation:

The data in Response Headers is the content sent by the browser to the website, including browser information and cookies.

status: 200 normal 418 crawler orz when found

(Package is required when 418 (User-Agent details see later))

 

 

Request core code:

In python3 urllib has been integrated with urllib2 library, just import urllib

import urllib.request

response = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode("utf-8"))

decode can decode it into text that is easy to browse.

 

 

POST related:

Test sites for commonly used posts:

httpbin.org

 

Post some data test (using bytes to convert into binary files) (simulating real user login (cookies))

import urllib.request,urllib.parse

if __name__ == '__main__':
    data = bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")
    response = urllib.request.urlopen("http://httpbin.org/post",data = data)
    print(response.read().decode("utf-8"))

 

Remember to use try...except urllib.error.URLError: to implement timeout error handling (commonly used) 

data = bytes(urllib.parse.urlencode({"hello": "world"}), encoding="utf-8")
    try:
        req = urllib.request.Request("http://douban.com", data=data, headers=headers, method="POST")
        response = urllib.request.urlopen(req)
        print(response.read().decode("utf-8"))
    except urllib.error.URLError as e:
        if hasattr(e,"code"):
            print(e.code)
        if hasattr(e,"reason"):
            print(e.reason)

 

Anti-418 operation: (also an example of the combination of request and response, use request to obtain the request instance with urlopen)

headers = {  #模拟浏览器头部信息 向豆瓣服务器发送消息
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36" #from your browser
}

data = bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")
    req = urllib.request.Request("http://douban.com",data = data,headers = headers, method = "POST")
    response = urllib.request.urlopen(req)
    print(response.read().decode("utf-8"))

 

 

BeautifulSoup:

Function: Convert a complex HTML document into a complex tree structure, each node is a Python object, all objects can be summarized into 4 types

(Powerful tool for searching html tags and content, avoiding heavy find work)

--Tag tag

--NavigableString

--BeautifulSoup

--Comment

 

Basic example:

from bs4 import BeautifulSoup

file = open("baidu.html","rb")
html = file.read()
bs = BeautifulSoup(html,"html.parser")


print(bs.a)# get tag
print(bs.title.string) # get string inside tag
print(bs.a.attrs) # get attrs inside tag

Common search functions:

bs.find_all("a") # 完全匹配
bs.find_all(re.compile("a")) # 正则匹配
bs.find_all(id = "head") # 寻找id为head的标签


# 方法搜索: 传入一个函数,根据函数的要求来搜索
def rules():
    return tag.has_attr("name")
bs.find_all(rules)

tlist = bs.select('title') # 通过标签来查找
tlist = bs.select('.mnav') # 通过类名来查找(# id)
tlist = bs.select('head > title') # 查找子标签
tlist = bs.select('.manv ~ .bri') # 查找兄弟标签
# 获取该文本的方法
print(tlist[0].get_text())

 

 

Guess you like

Origin blog.csdn.net/ShuoCHN/article/details/112389441