python - 值错误: Unsupported or invalid CSS selector: "unit-4" python

标签 python web-scraping beautifulsoup

我刚刚尝试使用 python、Beautifulsoup 进行网页抓取,以便从购物网站获取产品的 url。

这里我提供我的简单代码:

import requests
from bs4 import BeautifulSoup

root_url = 'http://www.flipkart.com'
index_url = root_url + '/tablets'

def get_item_url():
    response = requests.get(index_url)
    soup = BeautifulSoup(response.text)
    return [a.attrs.get('href') for a in soup.select('div.product-unit unit-    4 browse-product-section a[href^=/digiflip-pro-et701-tablet]') 


print(get_item_url())

运行该程序会生成如下错误:

File "C:\Python27\lib\site-packages\bs4\element.py", line 1300, in select
'Unsupported or invalid CSS selector: "%s"' % token)
ValueError: Unsupported or invalid CSS selector: "unit-4"

如何解决这个错误?

最佳答案

查看 Beautiful Soup 文档,我发现在 select() 中的属性之间放置了空格。搜索其他标签下面的标签。所以你的select()正在寻找名为 unit-4 的属性下面某处div.product-unit ,然后它正在寻找 browse-product-section下面unit-4 。不存在这样的属性,因此返回错误。

您的 select() 中的属性实际上是该网页上存在的 HTML 类的名称,因此您必须附加 .给他们每个人找到他们。但是,我认为您真正想要的更像是:

return [a.attrs.get('href') for a in soup.select('div.product-unit a[href^=/digiflip-pro-et701-tablet]')]

在该 div 下查找 href 并返回

['/digiflip-pro-et701-tablet/p/itme27y5v2ws5cfm?pid=TABDWMDPGHPNYND7', '/digiflip-pro-et701-tablet/p/itme27y5v2ws5cfm?pid=TABDWMDPGHPNYND7', '/digiflip-pro-et701-tablet/p/itme27y5v2ws5cfm?pid=TABDWMDPGHPNYND7&ref=70ca8997-80a5-412d-9b94-6d5fb55f1277', '/digiflip-pro-et701-tablet/p/itme27y5v2ws5cfm?pid=TABDWGBMYSEMWHUY&ref=70ca8997-80a5-412d-9b94-6d5fb55f1277']

顺便说一句,您也可以替换 div.product-unitunit-4 ,甚至做select('a[href^=/digiflip-pro-et701-tablet]')本身,你会得到相同的输出。

关于python - 值错误: Unsupported or invalid CSS selector: "unit-4" python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28168274/

相关文章:

python - 为什么我从网络抓取中得到空列表?

python - 使用 BeautifulSoup 解析 HTML

python - beautifulsoup findall

python - 无法easy_install ssl模块

python - Selenium 无法使用 python 抓取 Shopee 电子商务网站

python - Django : How to use LIKE while fetching data from mysql DB

python请求: (SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1123)'))

python - 使用 BeautifulSoup 解码 html 实体

python - 如何获取 cElementTree 中元素的所有文本子项?

python - Django 在外出进行 paypal 付款时保持登录丢失