【发布时间】:2020-03-20 05:00:24
【问题描述】:
希望你一切都好。今天早些时候,我按照类似的思路写了一个 HTML 网站的基本网络爬虫。我正在学习一个教程,你可以通过我的代码看到我对 Python 编码有点陌生。希望获得有关抓取此站点的一些指导。
从注释掉的代码可以看出,
#print(results.prettify())
我能够成功地打印出网页的全部内容。然而,我想做的是减少我打印出来的内容,所以我只是打印出相关的内容。页面上有很多我不想要的内容,我想把它按摩掉。有没有人想过为什么代码底部的 for 循环 not 按顺序抓取 HTML 的 xlmins 单元中的段落并将其打印出来?更多内容请查看以下代码。
import requests
from bs4 import BeautifulSoup
URL = "http://www.gutenberg.org/files/7142/7142-h/7142-h.htm"
page = requests.get(URL)
#we're going to create an object in Beautiful soup that will scrape it.
soup = BeautifulSoup(page.content, 'html.parser')
#this line of code takes
results = soup.find(xmlns='http://www.w3.org/1999/xhtml')
#print(results.prettify())
job_elems = results.find_all('p', xlmins="http://www.w3.org/1999/xhtml")
for job in job_elems:
paragraph = job.find("p", xlmins='http://www.w3.org/1999/xhtml')
print(paragraph.text.strip)
【问题讨论】:
标签: python python-3.x beautifulsoup python-requests python-requests-html