簡體   English   中英

美麗湯沒有選擇任何元素

[英]Beautiful Soup is not selecting any element

這是我用來遍歷所有元素的代碼:

soup_top = bs4.BeautifulSoup(r_top.text, 'html.parser')

selector = '#ContentPlaceHolder1_gvDisplay table tr td:nth-of-type(3) a'

for link in soup_top.select(selector):
    print(link)

在JavaScript中使用相同的選擇器時,其長度為57:

document.querySelectorAll("#ContentPlaceHolder1_gvDisplay table tr td:nth-of-type(3) a").length;

我以為也許我沒有正確獲取網頁的內容。 然后,我保存了網頁的本地副本,但“美麗湯”中的選擇器仍然沒有選擇任何內容。 這里發生了什么?

這是我正在使用代碼的網站

看來這是由於您使用了解析器 (即html.parser )。 如果我使用lxml作為解析器嘗試相同的操作:

from bs4 import BeautifulSoup
import requests

url = 'http://www.swapnilpatni.com/law_charts_final.php'
r = requests.get(url)
r.raise_for_status()

soup = BeautifulSoup(r.text, 'lxml')

css_select = '#ContentPlaceHolder1_gvDisplay table tr td:nth-of-type(3) a'
links = soup.select(css_select)
print('{} link(s) found'.format(len(links)))

>> 1 link(s) found

for link in links:
    print(link['href'])

>> spadmin/doc/Company Law amendment 1.1.png

html.parser將一直返回結果,直到#ContentPlaceHolder1_gvDisplay table tr為止,即使如此,它也僅返回第一個tr

通過W3標記驗證服務運行url時,將返回以下錯誤:

抱歉,我無法驗證此文檔,因為在第1212行上它包含一個或多個無法解釋為utf-8的字節(換句話說,找到的字節在指定的字符編碼中不是有效值)。 請檢查文件的內容和字符編碼指示。 錯誤是:utf8“ \\ xA0”沒有映射到Unicode

html.parser可能對此html.parser窒息,而lxml更具容錯能力。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM