BeautifulSoup入门案例

import beautifulsoup4 as bs
import requests

url = “http://www.baidu.com
html = requests.get(url) # 获取网页响应对象
html.encoding = ‘utf-8’ # 修改网页响应对象(requests.models.Response)的编码格式
content = html.text # 获取网页的内容
soup = bs(content, ‘html.parser’) # 根据网页内容创建一个beautifulsoup对象, 'html.parser’为网页解析器

print(soup.prettify()) # 格式化输出网页内容

a_tag_set = soup.find_all(‘a’) # 获取网页中的所有的a标签,返回值为一个集合
a_tag = soup.find('a‘) # 获取网页中的第一个a标签
a_tag = soup.a # 获取网页中的第一个a标签
a_dict = a_tag.attrs # 获取a标签的属性字典
print(a_dict[‘href’]) # 打印a标签中的’href’属性的值

a_parent_tag_iterator = soup.a.parent # .parent返回可迭代对象,不是列表,需要用for循环遍历其中的内容
a_children_tag_iterator = soup.a.children # .children返回可迭代对象,不是列表,需要用for循环遍历其中的内容

猜你喜欢

转载自blog.csdn.net/Gldwolf/article/details/88087787