【问题标题】:How to use CSS selectors to retrieve specific links using BeautifulSoup?如何使用 CSS 选择器使用 BeautifulSoup 检索特定链接?
【发布时间】:2021-08-30 22:06:39
【问题描述】:

我正在使用 python 来抓取以下页面:alfabeta.surge.sh,我想获取 (#home1 > div:nth-child(10) > table:nth-child(29) > tbody > tr 中的链接: nth-child(1) > td:nth-child(3) > a)

其实我是这样做的:

import bs4, requests
res = requests.get('https://alfabeta.surge.sh/')
soup = bs4.BeautifulSoup(res.text, 'html.parser')
soup.find_all('a')[23].attrs.get('href')

但是如果位置改变了我就不能下载内容了

【问题讨论】:

标签: python html css web-scraping beautifulsoup


【解决方案1】:

您需要对最有可能保持不变的内容做出一些假设,然后随着时间的推移进行审查。例如,我可能假设您想要第三列td 的子a 标记href,来自table,这是div 之后的第一个,包含字符串Catálogo Actualizaciones。一种css模式如下:

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://alfabeta.surge.sh/')
soup = bs(r.text, 'lxml')
print(soup.select_one('div:-soup-contains("Catálogo Actualizaciones") ~ table td:nth-child(3) > a')['href'])

【讨论】:

  • 我试图这样做,但响应 {NotImplementedError}':-soup-contains' 伪类目前没有实现
  • print(soup.select_one('div:contains("Catálogo Actualizaciones") ~ table td:nth-child(3) > a')['href'])
  • 或者将你的 bs4/soupsieve 升级到最新版本。
猜你喜欢
  • 2014-09-08
  • 2017-01-23
  • 2014-03-01
  • 2020-01-04
  • 1970-01-01
  • 2021-12-31
  • 2018-07-05
  • 2014-09-07
  • 1970-01-01
相关资源
最近更新 更多