【发布时间】:2016-09-16 23:15:35
【问题描述】:
我对 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)
我想要得到的是“UPC:813066012487,价格:26.45 和 SKU:KBPTMCC2”,没有任何跨度、元或内容属性。我在下面附上了我的输出 这是我的输出: screenshot
我哪里做错了? 希望有人能弄清楚!谢谢!!
【问题讨论】:
-
但是你期望什么输出?另外,您能否修复代码的缩进以使结构更清晰?我猜
def single_item下面的整个块应该缩进? -
先抓取所有链接,然后去每个链接并抓取(upc、price、sku)。
-
预期输出是什么
-
预期输出是这样的 813066012487 KBPTMCC2 26.45
-
添加您想要解决的问题。
标签: python web-scraping beautifulsoup