Python 如何使用CSS选择器获取正确的元素?
我正在努力求出每平方米的平均价格以及括号。我已经克服了第一个障碍(参见使用select而不是findAll),但现在我不能得到错误的结果。事实上,我想用我的图形获得Python 如何使用CSS选择器获取正确的元素?,python,html,web-scraping,beautifulsoup,css-selectors,Python,Html,Web Scraping,Beautifulsoup,Css Selectors,我正在努力求出每平方米的平均价格以及括号。我已经克服了第一个障碍(参见使用select而不是findAll),但现在我不能得到错误的结果。事实上,我想用我的图形获得元素,但我进入了其他元素(见下图) 我知道它与子节点和标记后面的小箭头有关,但我无法理解。。。 那么我该怎么做才能得到文本“2992欧元”和括号文本“1962欧元4 158欧元” 这是我的密码 import requests from bs4 import BeautifulSoup as bs res=requests.get(&
- 元素,但我进入了其他
- 元素(见下图) 我知道它与子节点和
- 标记后面的小箭头有关,但我无法理解。。。
那么我该怎么做才能得到文本“2992欧元”和括号文本“1962欧元4 158欧元”
这是我的密码
我得到的(上图)import requests from bs4 import BeautifulSoup as bs res=requests.get("https://www.meilleursagents.com/prix-immobilier/marseille-13000/") soup=bs(res.text,"html.parser") infos=soup.select("li",class_="big-number") print(infos)
我想要的(如上)转到开发工具,选择元素。然后单击复制为css选择器,浏览器会自动为您提供正确的css选择器。或者,您可以使用xpath。这里有一个解决方案,您可以尝试使用父标记
而不是ul
li
for ul in soup.find_all("ul", {"class": "prices-summary__price-range"}): for li in ul.find_all("li"): if li.string: print(li.string.strip())
它正在从服务器上指定的列表中查找有效的浏览器ua,并且需要处理unicodeimport requests from bs4 import BeautifulSoup import unicodedata import re headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'} r = requests.get('https://www.meilleursagents.com/prix-immobilier/marseille-13000/', headers = headers) soup = BeautifulSoup(r.text, "lxml") for i in soup.select('.prices-summary__price-range'): print([re.sub('\n\s+', '', unicodedata.normalize('NFKD', j.text.strip())) for j in i.select('li:nth-child(n+2):nth-child(-n+3)')])
这很奇怪。我复制了你的代码,并将其粘贴在
之后,但没有打印任何内容……嗯。。这很奇怪,只是看看响应是否包含所需的内容。我不认为是打印指令的问题,而是循环,因为在if指令之后,我添加了soup=bs(res.text,“html.parser”)
,它从不打印字母a,所以if永远不会被复制为css选择器行print(“a”)
- 并将其粘贴到我的代码中,如下所示:
但是它返回一个空列表(或者在使用find方法时不返回)很抱歉@OctoppuSS7我是一个初学者,所以可能我没有很好地应用你的建议如果你是一个初学者,这不是最好的解决方案,所以我会选择其他的解决方案。那么这可能有一行代码吗……我想我也可以试着解决它。你对我在问题中提到的问题有什么想法吗(在cf.page上)@octopus7非常感谢您的回答!!尽管有防刮机制,我还是可以得到正确的值!infos=soup.select(“prices summary sell>div.prices-summary\uu sell-prices--container>div.prices-summary\uu公寓价格>ul>li.big number”)
import requests from bs4 import BeautifulSoup import unicodedata import re headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'} r = requests.get('https://www.meilleursagents.com/prix-immobilier/marseille-13000/', headers = headers) soup = BeautifulSoup(r.text, "lxml") for i in soup.select('.prices-summary__price-range'): print([re.sub('\n\s+', '', unicodedata.normalize('NFKD', j.text.strip())) for j in i.select('li:nth-child(n+2):nth-child(-n+3)')])