Datawhale-爬虫-Task3(beautifulsoup)

Beautiful Soup

  • Beautiful Soup是一个非常流行的Python模块。该模块可以解析网页,并提供定位内容的便捷接口。
  • 使用Beautiful Soup的第一步是将已下载的HTML内容解析为soup文档。由于大多数网页都不具备良好的HTML格式,因此Beautiful Soup需要对其实际格式进行确定。

例如,在下面这个简单的网页列表中,存在属性值两侧引号缺失和标签未闭合的问题:

<ul class = country>
	<li>Area
	<li>Population
</ul>

如果Population列表项被解析为Area列表的子元素,而不是并列两个列表项的话,我们在抓取时就会得到错误的结果。下面我们看一下Beautiful Soup是如何处理的。

from bs4 import BeautifulSoup
broken_html = '<ul class=country><li>Area<li>Population</ul>'
soup = BeautifulSoup(broken_html,'html.parser')
fixed_html = soup.prettify()
print(fixed_html)
<ul class = "country">
	<li>Area</li>
	<li>Population</li>
</ul>

从上面结果可以看出,Beautiful soup能正确解析缺失的引号并闭合标签,现在我们就可以使用find()和findall()方法来定位我们需要的元素了。

案例:

使用beautifulsoup提取下面丁香园论坛的特定帖子的所有回复内容,以及回复人的信息。

  • 首先进去丁香园论坛查看源网页找到相关的HTML标签

发帖人:
在这里插入图片描述
帖子的内容:
在这里插入图片描述
发现这两个标签都是唯一的,所以直接使用find在HTML中找到标签即可:

user_id = item.find("div", "auth").get_text()
content = item.find("td", "postbody").get_text("|", strip=True)

所有代码:

import requests
from bs4 import BeautifulSoup as bs

def get_soup():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
    }
    url = 'http://www.dxy.cn/bbs/thread/626626'
    try:
        html = requests.get(url,headers = headers)
        if html.status_code == 200:
            return html.text
    except:
        pass

def get_item(html):
    topic_con = bs(html, 'lxml')
    table = topic_con.find_all('tbody')
    datas = []
    for item in table:
        try:
            user_id = item.find("div", "auth").get_text()
            content = item.find("td", "postbody").get_text("|", strip=True)
            datas.append((user_id, content))
        except:
            pass
    return datas


def main():
    html = get_soup()
    info = get_item(html)
    for x in info:
    	print(x)


if __name__ == '__main__':
    main()

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/TNTZS666/article/details/88087789
今日推荐