【发布时间】:2018-07-19 10:16:07
【问题描述】:
我有一个元组列表,我需要使用 pandas 将其放入 CSV 文件中,但不确定如何。我正在考虑将它们放入 dic 中,但没有奏效。这是我试图进入 CSV 的列表。
tables = soup.find_all("div", {"class":"pane"})[0].find_all("table")
if (len(tables) > 4):
product_list = [
(
t[0].findAll("div", {"class":"headline"})[0].text.strip(), #title
t[0].findAll("div", {"class":"copy"})[0].text.strip(), #description
t[1].text.strip(), #product number
t[2].text.strip(), #category number
t[3].text.strip() #price
)
for t in (t.find_all('td') for t in tables[4].find_all('tr'))
if t
]
elif (len(tables) == 1):
product_list = [
(
t[0].findAll("div", {"class":"catNo"})[0].text.strip(), #catNo
t[0].findAll("div", {"class":"headline"})[0].text.strip(), #headline
t[0].findAll("div", {"class":"price"})[0].text.strip(), #price
t[0].findAll("div", {"class":"copy"})[0].text.strip() #description
)
for t in (t.find_all('td') for t in tables[0].find_all('tr'))
if t
]
else:
print("could not parse main product\n\n")
time.sleep(timeDelay)
print(product_list)
time.sleep(timeDelay)
if len(tables) > 5:
add_product_list = [
(
t[0].findAll("div", {"class":"title"})[0].text.strip(), #title
t[0].findAll("div", {"class":"copy"})[0].text.strip(), #description
t[1].text.strip(), #product number
t[2].text.strip(), #category number
t[3].text.strip() #price
)
for t in (t.find_all('td') for t in tables[5].find_all('tr'))
if t
]
print(add_product_list)
time.sleep(timeDelay)
我已经导入了熊猫,但不知道要在数据框中放什么,因为它们并不是每个都被命名的特定项目,它们都被混为一谈。任何帮助都会很棒,因为这是我的拳头更高级的刮擦之一取得了。谢谢!
这也是脚本的第一部分,其中包含我正在抓取的 HTML/URL。
from bs4 import BeautifulSoup
import requests
import time
import random
import csv
import pandas as pd
f = pd.DataFrame
filename = "Qiagen_Scrape_final.csv"
f = open(filename, "w")
headers = "product_name, product discription, Cat No, product number, price\n"
f.write('headers')
product_urls =[
'https://www.qiagen.com/us/shop/pcr/primer-sets/miscript-precursor-assays/#orderinginformation',
'https://www.qiagen.com/us/shop/pcr/primer-sets/miscript-primer-assay-plate/#orderinginformation',
]
【问题讨论】:
-
你能分享一个你正在抓取的html样本吗?
-
这里是代码的第一部分,其中包含我正在使用的 html/ URL。
-
from bs4 import BeautifulSoup import requests import time import random import csv import pandas as pd f = pd.DataFrame filename = "Qiagen_Scrape_final.csv" f = open(filename, "w") headers = "product_name , 产品描述, 货号, 产品编号, 价格\n" f.write('headers') product_urls =[ 'qiagen.com/us/shop/pcr/primer-sets/miscript-precursor-assays/…', 'qiagen.com/us/shop/pcr/primer-sets/miscript-primer-assay-plate/…',
-
@briancaffey ...
-
一会儿,我查看了您要抓取的内容,我想我了解您面临的问题。有一个复杂的表结构。我想向您展示您可以从表中创建一个简单的 dict 到 pandas 数据框.. 片刻
标签: python pandas csv web-scraping beautifulsoup