Python爬虫实战之爬取网页元素内容
上篇文章,我借用了『整蛊网站』为大家来演示Python调用requests库爬取网页源代码。
而这一次,是上次代码的“升级版”。
什么是『元素内容』?举个栗子。
<title>fly6022</title>
<p>hello, world!</p>
形如<title>
与</title>
之间、<p>
与</p>
之间的信息就叫“元素内容”。
调用库
- requests
- beautifulsoup4
安装库
pip install beautifulsoup4
else
easy_install beautifulsoup4
代码
import requests
from bs4 import BeautifulSoup
print("键入URL:")
a = input()
ret = requests.get(a)
soup = BeautifulSoup(ret.content,"html.parser")
print(soup.title)
为变量a
赋值https://www.baidu.com/index.html
,输出的结果是:
<title>百度一下,你就知道</title>
类似的,通过对以上代码的微小修改,还可以获取到网页的其它元素信息,例如<head>
:
import requests
from bs4 import BeautifulSoup
print("键入URL:")
a = input()
ret = requests.get(a)
soup = BeautifulSoup(ret.content,"html.parser")
print(soup.head)
输出的结果是:
<head><meta content="text/html;charset=utf-8" http-equiv="content-type"/><meta content="IE=Edge" http-equiv="X-UA-Compatible"/><meta content="always" name="referrer"/><link href="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css"/><title>百度一下,你就知道</title></head>
其它