在两个不同标签之间提取文本美丽的汤

2024-04-27 12:42:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从this web page提取文章的文本内容。在

我只是想提取文章内容,而不是“关于作者部分”。在

问题是所有内容都不在<div>这样的标记中。因此,我无法提取它们,因为它们都在<p>标记内。当我提取所有的<p>标记时,我还得到了“关于作者”部分。我得从这个网站上搜很多页。有没有办法用靓汤来做这个?在

我正在尝试:

p_tags=soup.find_all('p')
for row in p_tags:
    print(row)

Tags: 标记文本divweb内容网站文章tags
3条回答

如果您想将About the author与不在段落中的内容一起踢出,可以通过在类td-post-content内打印p标记下的span标记的内容来完成。为了简洁起见,我在本例中使用选择器。也试试下面的方法。在

import requests
from bs4 import BeautifulSoup

url = 'https://www.the-blockchain.com/2018/06/29/mcafee-labs-report-6x-increase-in-crypto-mining-malware-incidents-in-q1-2018/'

res = requests.get(url,headers={"User-Agent":"defined"})
soup = BeautifulSoup(res.text, 'lxml')
paragraph = [p.text for p in soup.select('.td-post-content p span')]
print(paragraph)

您需要使用selenium,因为我试图用requests来完成,但它不起作用,因为数据是用javascript加载的,后面跟着bs4

import requests, bs4
from selenium import webdriver

driver = webdriver.Chrome('/usr/local/bin/chromedriver') 
website = "https://www.the-blockchain.com/2018/06/29/mcafee-labs-report-6x-increase-in-crypto-mining-malware-incidents-in-q1-2018/"
driver.get(website) 
html = driver.page_source
soup = bs4.BeautifulSoup(html, "html.parser")

elements = soup.select('#wpautbox_latest-post > ul > li')
for elem in elements:
    print(elem.text)

输出

^{pr2}$

您需要的所有段落都位于<div class="td-post-content">标记内,以及作者信息的段落。但是,必需的<p>标记是此<div>标记的直接子标记,而其他不需要的{}标记不是直接子标记(它们嵌套在其他div标记中)。在

因此,您只能使用^{}来访问这些标记。在

代码:

import requests
from bs4 import BeautifulSoup

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}

r = requests.get('https://www.the-blockchain.com/2018/06/29/mcafee-labs-report-6x-increase-in-crypto-mining-malware-incidents-in-q1-2018/', headers=headers)
soup = BeautifulSoup(r.text, 'lxml')

container = soup.find('div', class_='td-post-content')
for para in container.find_all('p', recursive=False):
    print(para.text)

输出:

^{pr2}$

相关问题 更多 >