web-scraping – 使用BeautifulSoup匹配html标记中的确切类

我正在使用Beautiful Soup从网站上抓取信息.

相关代码:

page_url = https://www.autotrader.co.uk/car-search?sort=sponsored&radius=1500&postcode=&onesearchad=Used&onesearchad=Nearly%20New&onesearchad=New&make=Vauxhall&model=Corsa&year-from=2008&year-to=2010&minimum-mileage=82376&maximum-mileage=123564&page=2

page = urllib2.urlopen(page_url)

soup = BeautifulSoup(page,'html.parser')

现在我只想在< div class =“vehicle-price”>< / div>内的页面上打印每个价格.标签,例如:

<div class="vehicle-price" data-label="search appearance click">\xa34,400</div>

所以我使用:

for i in soup.select('div.vehicle-price'):
    print (i.string)

这工作正常除了有一些< div>像这样的标签:

<div class="vehicle-price physical-stock-mrrp" data-label="search 
appearance click new car">

代码仍会打印这些标签中的内容.

当class =“vehicle-price”而不是class =“vehicle-price other-things-too”时,我如何告诉Beautiful Soup我只想要标签内容?

解决方法

您可以使用 :not() CSS pseudo-class排除其他类

.vehicle-price:not(.physical-stock-mrrp)

BeautifulSoup 4.7.1

例如,您可以使用Or语言进行链接.示例链接将是.vehicle-price:not(.physical-stock-mrrp),. vehicle-price:not(.somethingElse).其他选择器的想法可能包括传递attribute = value选择器并使用^,*,$运算符来指定要在属性值中匹配的子字符串.显然,感谢@facelessuser,您还可以将选择器列表传递给:not.

相关文章

HTML代码中要想改变字体颜色,常常需要使用CSS样式表。CSS是...
HTML代码如何让字体盖住图片呢?需要使用CSS的position属性及...
HTML代码字体设置 在HTML中,我们可以使用标签来设置网页中的...
在网页设计中,HTML代码的字体和字号选择是非常重要的一个环...
HTML(Hypertext Markup Language,超文本标记语言)是一种用...
外链是指在一个网页中添加一个指向其他网站的链接,用户可以...