[英]BeautifulSoup nth-of-type returns empty list. Soup.select()[n -1] returns the elements. Why?
[英]beautifulSoup soup.select() returning empty for css selector
我正在尝试解析来自该站点https://news.ycombinator.com/的一些链接
我想 select 一个特定的表
document.querySelector("#hnmain > tbody > tr:nth-child(3) > td > table")
我知道 bs4 的 css 选择器限制。 但问题是我什至不能像#hnmain > tbody
with soup.select('#hnmain > tbody')
这样简单的 select 因为它返回空
使用下面的代码,我无法解析 tbody 而使用 js 我做了(截图)
from bs4 import BeautifulSoup
import requests
print("-"*100)
print("Hackernews parser")
print("-"*100)
url="https://news.ycombinator.com/"
res=requests.get(url)
html=res.content
soup=BeautifulSoup(html)
table=soup.select('#hnmain > tbody')
print(table)
出去:
soup=BeautifulSoup(html)
[]
而不是通过正文和表格为什么不直接到链接 go 呢? 我对此进行了测试,效果很好:
links=soup.select('a',{'class':'storylink'})
如果你想要表格,因为每页只有一个,你不需要 go 通过其他元素 - 你可以 go 直接到它。
table = soup.select('table')
我没有从 beautifulsoup 或 curl 脚本中获得 html 标签tbody 。 它的意思是
soup.select('tbody')
返回空列表。 这与您获得空列表的原因相同。
要提取您正在寻找的链接,只需执行
soup.select("a.storylink")
它将从站点获取您想要的链接。
数据以 3 行为一组排列,其中第三行是用于间隔的空行。 循环顶部行并使用 next_sibling 在每个点获取关联的第二行。 BS4 4.7.1+
from bs4 import BeautifulSoup as bs
import requests
r = requests.get('https://news.ycombinator.com/')
soup = bs(r.content, 'lxml')
top_rows = soup.select('.athing')
for row in top_rows:
title = row.select_one('.storylink')
print(title.text)
print(title['href'])
print('https://news.ycombinator.com/' + row.select_one('.sitebit a')['href'])
next_row = row.next_sibling
print(next_row.select_one('.score').text)
print(next_row.select_one('.hnuser').text)
print(next_row.select_one('.age a').text)
print(next_row.select_one('a:nth-child(6)').text)
print(100*'-')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.