网络爬虫python入门基础篇
网络爬虫python入门基础篇
# 1 url
# ========================================
import urllib.request response = urllib.request.urlopen('http://www.baidu.com') buff = response.read() html = buff.decode("utf8") print(html)
# 2 携带参数
# ========================================
import urllib.request import urllib.parse url = 'http://www.baidu.com' values = {'name': 'voidking','language': 'Python'} data = urllib.parse.urlencode(values).encode(encoding='utf-8',errors='ignore') headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0' } request = urllib.request.Request(url=url, data=data,headers=headers,method='GET') response = urllib.request.urlopen(request) buff = response.read() html = buff.decode("utf8") print(html)
# 3 添加处理器
# ========================================
import urllib.request import http.cookiejar # 创建cookie容器 cj = http.cookiejar.CookieJar() # 创建opener opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) # 给urllib.request安装opener urllib.request.install_opener(opener) # 请求 request = urllib.request.Request('http://www.baidu.com/') response = urllib.request.urlopen(request) buff = response.read() html = buff.decode("utf8") print(html) print(cj)
# 4 install 网页解析器(BeautifulSoup)
# ========================================
sudo apt-get install python3-pip sudo pip3 install beautifulsoup4 import bs4 print(bs4)
# 5 install 网页解析器(BeautifulSoup)
# ========================================
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ soup = BeautifulSoup(html_doc) print(soup.prettify())
# 6 网页解析器(BeautifulSoup)soup.
# # ========================================
# 2、访问节点 print(soup.title) print(soup.title.name) print(soup.title.string) print(soup.title.parent.name) print(soup.p) print(soup.p['class']) # 3、指定tag、class或id print(soup.find_all('a')) print(soup.find('a')) print(soup.find(class_='title')) print(soup.find(id="link3")) print(soup.find('p',class_='title')) # 4、从文档中找到所有<a>标签的链接 for link in soup.find_all('a'): print(link.get('href'))
浙公网安备 33010602011771号