【问题标题】:web scraping price zero problem from a site从网站抓取价格为零的问题
【发布时间】:2020-03-10 16:16:22
【问题描述】:

嗨,我想从这段代码中获取价格

import re
import requests
from bs4 import BeautifulSoup
list3 = []
r = requests.get('https://bama.ir/car/peugeot/')
soup = BeautifulSoup(r.text, 'html.parser')
res2 = soup.find_all('div', attrs={'class':'listdata'})
for item in res2:
    z = re.findall(r'<span itemprop="price" content="([^"]*)">[^<]*</span>',str(item))
    list3 += z

for item in list3:
    print(item)

但此代码不返回“0”价格。我也想要“0”价格。 有人可以帮我吗?

【问题讨论】:

  • 根据您的正则表达式,所有价格都不是0
  • 如何在这个正则表达式中添加一个零?
  • [^"] 已经占零了。它是一个否定集,意思是“找到所有不是双引号的东西”,而零不是双引号。正则表达式是正确的,但您的 items 都不包含零。
  • 我的一些项目是“0”。这个正则表达式不显示“0”
  • 你的 HTML 是什么样的?

标签: python regex web-scraping beautifulsoup


【解决方案1】:

我猜,您可能希望在 content 属性中返回 0s,这可能很接近:

import re
import requests
from bs4 import BeautifulSoup
list3 = []
r = requests.get('https://bama.ir/car/peugeot/')
soup = BeautifulSoup(r.text, 'html.parser')
res2 = soup.find_all('div', attrs={'class': 'listdata'})
# print(res2)
for item in res2:
    z = re.findall(r'content="(\d*)"', str(item))
    list3 += z

for item in list3:
    print(item)

输出

145000000
145000000
77000000
77000000
0
116000000
116000000
106000000
106000000
105000000
105000000
0
58000000
3600000
0
0
142800000
142800000
35000000
35000000
0

如果您希望简化/修改/探索表达式,在regex101.com 的右上角面板中已对此进行了说明。如果您愿意,您还可以在this link 中观看它如何与一些示例输入匹配。


【讨论】:

  • 用字典语法简单地提取内容属性不是更干净吗?
  • [i['content'] for i in soup.select('.listdata[content]')]
  • 我所看到的你的答案没有错,并且解释非常好。只是一个想法。
【解决方案2】:

我终于用这段代码来获取零的数字

import re
import requests
from bs4 import BeautifulSoup
list3 = []
r = requests.get('https://bama.ir/car/peugeot/')
soup = BeautifulSoup(r.text, 'html.parser')
res2 = soup.find_all('div', attrs={'class': 'overview'})
for item in res2:
    z1 = re.findall(r'content="([0-9])"',str(item))
    list3 += z1
    z2 = re.findall(r'<!-- <p class="cost"><span itemprop="price" content="(\d*)">',str(item))
    list3 += z2
for item in list3:
    print(item)

感谢您的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2012-05-01
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多