【发布时间】:2018-02-06 09:49:20
【问题描述】:
我正在尝试使用 BeautifulSoup4 打印新闻文章的内容。
网址是:Link
我拥有的当前代码如下,它给出了所需的输出:
page = requests.get('http://www.thehindu.com/news/national/People-showing-monumental-patience-queuing-up-for-a-better-India-says-Venkaiah/article16447029.ece')
soup = BeautifulSoup(page.content, 'html.parser')
article_text = ""
table = soup.find_all("div",{ "id": "content-body-14266949-16447029"})
for element in table:
article_text += ''.join(element.find_all(text = True)) + "\n\n"
print(article_text)
但是,问题是我想抓取多个页面,每个页面都有不同的内容正文编号,格式为 xxxxxxxx-xxxxxxxx(2 块 8 位)。
我尝试用正则表达式替换 soup.find_all 命令:
table = soup.find_all(text=re.compile("content-body-........-........"))
但这会报错:
AttributeError: 'NavigableString' 对象没有属性 'find_all'
谁能指导我需要做什么?
谢谢。
【问题讨论】:
-
您希望所有作为 href 的链接都打印为输出吗?
-
没有。我正在尝试打印文章的文本。 soup.find_text() 给了我整个文本,而我需要的内容嵌入到中的多个
元素中,id 为 content-body-xxxxxxxx-xxxxxxxx。
标签: python web-scraping beautifulsoup