如何使用BeautifulSoup和Python从类似元素中仅提取特定文本

2024-09-30 05:33:44 发布

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

我说的网站:http://www.animenewsnetwork.com/encyclopedia/anime.php?id=160

你不能通过正常的请求废弃这个网站,这是不允许的。因此,我使用硒。现在,我的问题是:

我一直在试着从“流派”领域获取文本。如您所见,在第页上,它显示如下:

Genres: adventure, comedy, science fiction

刮削的问题是,这些链接附加到它们,当我刮削数据时,我不能只刮削文本。它还向我展示了类,链接到这些流派。你知道吗

我现在的代码:

driver.get('http://www.animenewsnetwork.com/encyclopedia/anime.php?id=160')

elem = driver.find_element_by_xpath("//*")
source_codeANN = elem.get_attribute("outerHTML")
soup2 = BeautifulSoup(source_codeANN, 'html.parser')
Genre = soup2.find_all('div',{'id':'infotype-30'})
print Genre

Tags: 文本comidhttpget网站链接www
3条回答

如果您有以下HTML

<div id="infotype-30" class="encyc-info-type br same-width-as-main" style="width: auto;">
    <strong>Genres:</strong> 
    <span><a href="/encyclopedia/search/genreresults?w=series&amp;a=AA&amp;a=OC&amp;a=TA&amp;a=MA&amp;g=adventure/A&amp;o=rating" class="discreet">adventure</a></span>,
    <span><a href="/encyclopedia/search/genreresults?w=series&amp;a=AA&amp;a=OC&amp;a=TA&amp;a=MA&amp;g=comedy&amp;o=rating" class="discreet">comedy</a></span>,
    <span><a href="/encyclopedia/search/genreresults?w=series&amp;a=AA&amp;a=OC&amp;a=TA&amp;a=MA&amp;g=science%20fiction&amp;o=rating" class="discreet">science fiction</a></span>
</div>

您可以获得以下类型链接的值:

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get('http://www.animenewsnetwork.com/encyclopedia/anime.php?id=160')
elem = driver.find_element_by_xpath("//*")
source_codeANN = elem.get_attribute("outerHTML")
soup2 = BeautifulSoup(source_codeANN, 'html.parser')
genre_div = soup2.find('div', id='infotype-30')
genres = [ a.text for a in genre_div.find_all('a') ]
print genres
# [u'adventure', u'comedy', u'science fiction']

我建议用Genres:文本和join查找strong元素的以下所有同级:

", ".join(elm.text for elm in driver.find_elements_by_xpath("//strong[. = 'Genres:']/following-sibling::*"))

演示:

>>> from selenium import webdriver
>>> driver = webdriver.PhantomJS()
>>> driver.get("http://www.animenewsnetwork.com/encyclopedia/anime.php?id=160")  
>>> ", ".join(elm.text for elm in driver.find_elements_by_xpath("//strong[. = 'Genres:']/following-sibling::*"))
u'adventure, comedy, science fiction'

请试试这个

driver.get("http://www.animenewsnetwork.com/encyclopedia/anime.php?id=160");
elem = driver.find_element_by_id("infotype-30")
print elem.text

相关问题 更多 >

    热门问题