与find_all的BeautifulSoup不完整的孩子

时间:2017-11-04 02:45:09

标签: python html web-scraping beautifulsoup findall

我正在试图从以下HTML脚本中删除“product-tech-section-row”类下的嵌套div实例:

<h2 class="product-tech-section-title">
    Présentation de la TV SAMSUNG UE49MU9005</h2>

<div class="product-tech-section-row">
    <div>
        Désignation</b> :
    </div>
    <div>
        <b>SAMSUNG UE49MU9005</b> (UE 49MU9005 TXXC)<br><br>Plus d'informations sur les <a             href="http://www.lcd-compare.com/info-tv-led-samsung.htm" title="TV Samsung : informations et statistiques">TV LED Samsung</a><br><a href="http://www.lcd-compare.com/tv-liste-122.htm?tv_label=7,8" title="Liste des TV 4K">Voir les TV 4K (Ultra HD ou Quad HD)</a></div>
</div>


<div class="product-tech-section-row">
    <div>
        Date de sortie (approx.)</b> :
    </div>
    <div>
        Mars 2017</div>
</div>

但是,使用find_all()只会提取第一个div子节点(仅Désignation,SAMSUNG UE ...不会出现),如下面的代码所示。我错过了什么吗?非常感谢帮助。

from urllib.request import urlopen as uReq
from urllib.request import Request
from bs4 import BeautifulSoup as soup

#Allowing access to the website (personal use)
prod_url="http://www.lcd-compare.com/televiseur-SAMUE49MU9005-SAMSUNG-UE49MU9005.htm"
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(prod_url,headers=hdr)
prod_html=uReq(req)

#Parsing the technical details
tec_list = prod_soup.find_all("div",{"class","product-tech-section-row"})

---------------------------------------------------------------------------------------
#However, this is what I am getting:
>>>print(tec_list[0])
<div class="product-tech-section-row">
<div>
Désignation</div></div>

>>>print(tec_list[0].findChildren())
[<div>
 Désignation<\div>]

1 个答案:

答案 0 :(得分:0)

我相信您可以废弃嵌套元素的原因是您访问的网站大量呈现Javascript。

我已经使用selenium来验证是否是这种情况,并且我能够正常解析嵌套元素而没有任何问题。

代码:

from selenium import webdriver
from bs4 import BeautifulSoup

chromeOptions = Options()  
chromeOptions.add_argument("--headless")  
driver = webdriver.Chrome(chrome_options=chromeOptions)
url = 'http://www.lcd-compare.com/televiseur-SAMUE49MU9005-SAMSUNG-UE49MU9005.htm'
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
tec_list = soup.findAll("div",{"class","product-tech-section-row"})

print(tec_list[0])

输出:

<div class="product-tech-section-row">
<div>
Désignation :
</div>
<div>
<b>SAMSUNG UE49MU9005</b> (UE 49MU9005 TXXC)<br/><br/>Plus d'informations sur les <a data-hasqtip="139" href="http://www.lcd-compare.com/info-tv-led-samsung.htm" oldtitle="TV Samsung : informations et statistiques" title="">TV LED Samsung</a><br/><a data-hasqtip="141" href="http://www.lcd-compare.com/tv-liste-122.htm?tv_label=7,8" oldtitle="Liste des TV 4K" title="">Voir les TV 4K (Ultra HD ou Quad HD)</a></div>
</div>