python 使用select_one()时出错,但find()方法可以正常工作

mzmfm0qo  于 2023-01-29  发布在  Python
关注(0)|答案(1)|浏览(145)

这是我的代码,当我把它转换成select_one()方法时,它给了我错误。
代码:

response = requests.get("https://near.org/blog/",headers=headers)
soup = BeautifulSoup(response.text, 'lxml').find("div", class_="bg-[#ffffff] grow rounded-br-[10px] rounded-bl-[10px] sm:rounded-bl-[0px] sm:rounded-tr-[10px] sm:rounded-br-[10px] py-[12px] px-[20px]").find("a").text.strip()
print(soup)

select_one()方法代码:

response = requests.get("https://near.org/blog/",headers=headers)
soup = BeautifulSoup(response.text, 'lxml').select_one("div.bg-[#ffffff].grow.rounded-br-[10px].rounded-bl-[10px].sm:rounded-bl-[0px].sm:rounded-tr-[10px].sm:rounded-br-[10px].py-[12px].px-[20px] a").text.strip()
print(soup)

第一个代码给我正确的输出,但第二个代码给我这个错误:

AttributeError: 'NoneType' object has no attribute 'text'
qnakjoqk

qnakjoqk1#

下面是在BeautifulSoup中使用select的正确方法,以您的示例为例:

import requests
from bs4 import BeautifulSoup as bs

headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
}

response = requests.get("https://near.org/blog/",headers=headers)
soup = bs(response.text, 'lxml').select_one('div[class="bg-[#ffffff] rounded-br-[10px] rounded-bl-[10px] sm:rounded-bl-[0px] sm:rounded-tr-[10px] md:rounded-[10px] py-[12px] px-[20px] w-[100%]"] a').text.strip()
print(soup)

最终结果:

NEAR’s Private Shard: Infrastructure for Enterprise, Built on the Open Web

您可以在here中找到BeautifulSoup文档。

相关问题