python最简单的爬虫——获取网页的html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 1、导入爬虫模块(第三方模块,需要提前安装)
import requests

# 2、把网址先赋值给变量url
url = 'http://www.baidu.com'

# 3、写入headers模拟浏览器上网,避免出现个别网站拒绝访问的情况
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",}

# 4、模拟浏览器发送http请求,并把结果赋值给变量response
response = requests.get(url,headers=headers)

# 5、修改编码方式(防止出现乱码)
response.encoding = 'utf-8'

# 6、网站源码(必须写.text,不然无法输出html代码)
html = response.text

# 7、输出
print(html)


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!