0%

python小菜鸟备忘录:用python做简易爬虫

小菜鸟开始爬虫之旅了!记录一下!

安装库

安装 requests 库

1
python3 -m pip install requests

安装 beautifulsoup4

1
python3 -m pip install beautifulsoup4

爬取网页

import库

1
2
import requests
from bs4 import BeautifulSoup

指定 url 并提取网页内容

1
2
3
4
5
6
7
8
url = "https://……"
r = requests.get(url)
html_doc = r.text

#if 要加headers
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}
r = requests.get(res_url, headers=headers)
html_doc = r.text

处理网页内容

初始化 beautifulsoup4

1
Soup = BeautifulSoup(html_doc, 'lxml')

寻找需要的部分

1
2
3
4
5
6
7
8
9
10
#网页里包含多个相同class的内容
cols = Soup.find_all('div', class_='col2 articleDetailTeaser')
for i in range(len(cols)):
all_a = cols[i].find_all('a') #找到所有指定class底下的链接
for j in range(len(all_a)):
res_url = all_a[j]['href'] #['href']后就是真的链接

#网页里只有一个相同class的内容
links = Soup.find('div', class_='linkList download')
link = links.find('a')['href']

下载指定链接文件

pdf

1
2
3
4
target_file = requests.get(url)
fo = open('name.pdf','wb')
fo.write(target_file.content)
fo.close()

mp3

1
2
3
4
5
target_file = requests.get(url,stream=True)
fo = open('name.mp3','ab')
fo.write(res.content)
fo.flush()
fo.close()

其他处理

速度减慢

1
2
import time
time.sleep(0.2)