我对Python还很陌生,主要需要它从网站上获取信息。你知道吗
def spider(max_pages):
page = 1
while page <= max_pages:
url = 'https://www.example.com'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
for link in soup.findAll('a', {'class': 'c5'}):
href = link.get('href')
time.sleep(0.3)
# print(href)
single_item(href)
page += 1
def single_item(item_url):
s_code = requests.get(item_url)
p_text = s_code.text
soup = BeautifulSoup(p_text, "html.parser")
upc = ('div', {'class': 'product-upc'})
for upc in soup.findAll('span', {'class': 'upcNum'}):
print(upc.string)
sku = ('span', {'data-selenium': 'bhSku'})
for sku in soup.findAll('span', {'class': 'fs16 c28'}):
print(sku.text)
price = ('span', {'class': 'price'})
for price in soup.findAll('meta', {'itemprop': 'price'}):
print(price)
outFile = open(r'C:\Users\abc.txt', 'a')
outFile.write(str(upc))
outFile.write("\n")
outFile.write(str(sku))
outFile.write("\n")
outFile.write(str(price))
outFile.write('\n')
outFile.close()
spider(1)
我想要的是“通用产品代码:813066012487, 价格:26.45和库存单位:KBPTMCC2“没有任何span、meta或content属性。我将输出附加在下面 以下是我的输出: screenshot
我哪里做错了? 希望有人能弄明白!谢谢!!你知道吗
您需要的数据位于div属性data itemdata中,您可以调用
json.loads
,它将为您提供一个dict,您可以访问该dict来获取您想要的内容:每个数据dict看起来像:
所以只要按键访问,即
price = data["price"]
。你知道吗要获取UPC我们只需要访问items页面,我们可以使用data-selenium属性从h3获取url:
并非所有页面都有UPC值,因此,如果您只希望产品具有UPC的第一个检查项(如果select发现任何内容),则必须决定要执行的操作:
相关问题 更多 >
编程相关推荐