2.1 BeautifulSoup 解析网页: 基础
要输出< h1>标题, 可以就直接soup.h1:
soup = BeautifulSoup(html, features='lxml')
print(soup.h1)
"""
<h1>爬虫测试1</h1>
"""
print('\n', soup.p)
"""
<p>
这是一个在 <a href="https://morvanzhou.github.io/">莫烦Python</a>
<a href="https://morvanzhou.github.io/tutorials/scraping">爬虫教程</a> 中的简单测试.
</p>
"""
如果网页中有多个同样的 tag, 比如链接< a>, 可以使用find_all来找到所有的选项. 因为真正的 link 不是在< a>中间< /a>,而是在< a href = 'link'>里面, 也可以看做是< a>的一个属性.用像 Python 字典的形式, 用 key 来读取l['href']
"""
<a href="https://morvanzhou.github.io/tutorials/scraping">爬虫教程</a>
"""
all_href = soup.find_all('a')
all_href = [l['href'] for l in all_href]
print('\n', all_href)
# ['https://morvanzhou.github.io/', 'https://morvanzhou.github.io/tutorials/scraping']
Last updated
Was this helpful?