python - 无法在 .select() 方法中使用多个属性

标签 python python-3.x web-scraping beautifulsoup css-selectors

我用 python 编写了一个脚本,用于从网站获取不同帖子的不同链接。如果我选择任何单个属性,例如 a[href^='/questions/'].question-hyperlink,我可以获得所需的输出。

My question is: how can I use two attributes from the same node within the .select() method like I've tried below?

到目前为止我的尝试(没有结果;也没有错误):

import requests
from bs4 import BeautifulSoup

link = "https://stackoverflow.com/questions/tagged/web-scraping"

res = requests.get(link)
soup = BeautifulSoup(res.text,'lxml')
for item in soup.select("a[href^='/questions/'].question-hyperlink"):
    print(item.get("href"))

最佳答案

实际上,您的代码运行良好。我得到了你预期的结果。我只需 pip install lxml 和 BeautifulSoup4 即可运行它。

/questions/54035304/unable-to-use-multiple-attributes-within-select-method
/questions/54035268/div-returns-empty-while-scraping-price-using-beautifulsoup-everything-else-lik
/questions/54035199/scrapy-restart-scrapoxy-instances
/questions/54034484/how-i-can-read-multiple-web-addresses-with-sign-in-address-that-block-dynami

附注您需要使用最新的 lxmlbs4 版本。所以你可能需要执行

  • pip3 install lxml --upgrade
  • pip3 install beautifulsoup4 --upgrade

关于python - 无法在 .select() 方法中使用多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54035304/

相关文章:

python - 如何使用具有多个参数的函数运行多处理 python 请求

javascript - 如何使用 Cheerio.js 从文档中删除 <!doctype html>

java - 位置 0 处出现意外字符 (B)

python - 如何让 argparse 使用选项而不是前缀从文件中读取参数

python - CircleCI 没有获取运行步骤中定义的环境变量?

python-3.x - 你能解释一下为什么情节在 J 处停止(在索引 10 处)

python - 在Python中调用有返回值的方法

python - Python 中整数的 O(1) 可索引双端队列

python - 如何让 QThreads 在控制台 PySide 程序中工作?

python-3.x - 如何更改 cx_Freeze 创建 "build"和 "dist"文件夹的目录?