作者okeyla (小寶)
看板Python
標題[問題] BeautifulSoup反選擇
時間Sun Jul 23 09:50:06 2017
不知BeautifulSoup可否反選擇呢?
以下是問題範例...
##################################
HTML2 = """
<table>
<tr>
<td class>a</td>
<td class>b</td>
<td class>c</td>
<td class>d</td>
</tr>
<tr>
<td class>e</td>
<td class>f</td>
<td class>g</td>
<td class>h</td>
</tr>
</table>
<table cellpadding="0">
<tr>
<td class>111</td>
<td class>222</td>
<td class>333</td>
<td class>444</td>
</tr>
<tr>
<td class>555</td>
<td class>666</td>
<td class>777</td>
<td class>888</td>
</tr>
"""
soup2 = BeautifulSoup(HTML2, 'html.parser')
f2 = soup2.select('table[cellpadding!="0"]') #<---關鍵在此
for div in f2:
row = ''
rows = div.findAll('tr')
for row in rows:
if(row.text.find('td') != False):
print(row.text)
##################################
我想把英文內容個table的td全都取出來,
按如下的形式存到excel當中.
a b c d
e f g h
但怎麼都是取到數字內容的表格.
Is there a hint?
Thanks!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.160.98.32
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1500774608.A.113.html
→ AlaRduTP: select 我不確定,但是可以把 !="0",改成 =None 試試 07/23 12:15
→ AlaRduTP: 看 07/23 12:15
→ okeyla: 頭大, 還是不成功... 07/23 15:13
推 LessonWang: 既然select方法無法奏效 07/23 15:48
→ LessonWang: 那你可以使用find_all方法xd 07/23 15:48
→ LessonWang: 畢竟bs4不支援css的not選擇器 07/23 15:48
→ LessonWang: 只好轉個彎吧 07/23 15:48
→ Sunal: 如果你會jQuery的話可以試試 pyquery 已打算拋棄bs惹 07/23 19:00
→ AlaRduTP: soup.find_all('table', attrs={'cellpadding': None}) 07/23 19:09
→ AlaRduTP: 或者用 soup.find() 就可以惹 07/23 19:11