正在清理从 BeautifulSoup 写入文本文件的数据
Cleaning up data written from BeautifulSoup to Text File
我正在尝试编写一个程序,从 ebay 产品页面收集特定信息并将该信息写入文本文件。为此,我使用 BeautifulSoup 和 Requests,并且我正在使用 Python 2.7.9。
我主要使用本教程 (Easy Web Scraping with Python) 并进行了一些修改。到目前为止,一切都按预期工作,直到它写入文本文件。资料都写好了,只是不是我想要的格式。
我得到的是:
{'item_title': u'Old Navy Pink Coat M', 'item_no': u'301585876394', 'item_price': u'US .00', 'item_img': 'http://i.ebayimg.com/00/s/MTYwMFgxMjAw/z/Sv0AAOSwv0tVIoBd/$_35.JPG'}
我所希望的是一些更容易使用的东西。
例如:
New Shirt 5555555555 US .00 http://ImageURL.jpg
换句话说,我只想要刮掉的文本,而不是方括号、'item_whatever' 或 u'。
经过一番研究后,我怀疑我的问题与写入文本文件时的信息编码有关,但我不确定如何解决它。
到目前为止我已经尝试过了,
def collect_data():
with open('writetest001.txt','w') as x:
for product_url in get_links():
get_info(product_url)
data = "'{0}','{1}','{2}','{3}'".format(item_data['item_title'],'item_price','item_no','item_img')
x.write(str(data))
希望它能让数据更容易按照我想要的方式进行格式化。它只导致 "NameError: global name 'item_data' is not defined" 在 IDLE 中显示。
我也尝试过在不同的位置使用.split()
和.decode('utf-8')
,但只收到AttributeErrors或者书面结果没有改变。
这是程序本身的代码。
import requests
import bs4
#Main URL for Harvesting
main_url = 'http://www.ebay.com/sch/Coats-Jackets-/63862/i.html?LH_BIN=1&LH_ItemCondition=1000&_ipg=24&rt=nc'
#Harvests Links from "Main" Page
def get_links():
r = requests.get(main_url)
data = r.text
soup = bs4.BeautifulSoup(data)
return [a.attrs.get('href')for a in soup.select('div.gvtitle a[href^=http://www.ebay.com/itm]')]
print "Harvesting Now... Please Wait...\n"
print "Harvested:", len(get_links()), "URLs"
#print (get_links())
print "Finished Harvesting... Scraping will Begin Shortly...\n"
#Scrapes Select Information from each page
def get_info(product_url):
item_data = {}
r = requests.get(product_url)
data = r.text
soup = bs4.BeautifulSoup(data)
#Fixes the 'Details about ' problem in the Title
for tag in soup.find_all('span',{'class':'g-hdn'}):
tag.decompose()
item_data['item_title'] = soup.select('h1#itemTitle')[0].get_text()
#Grabs the Price, if the item is on sale, grabs the sale price
try:
item_data['item_price'] = soup.select('span#prcIsum')[0].get_text()
except IndexError:
item_data['item_price'] = soup.select('span#mm-saleDscPrc')[0].get_text()
item_data['item_no'] = soup.select('div#descItemNumber')[0].get_text()
item_data['item_img'] = soup.find('img', {'id':'icImg'})['src']
return item_data
#Collects information from each page and write to a text file
write_it = open("writetest003.txt","w","utf-8")
def collect_data():
for product_url in get_links():
write_it.write(str(get_info(product_url))+ '\n')
collect_data()
write_it.close()
你走在正确的轨道上。
您需要一个局部变量来将 get_info
的结果分配给。您尝试引用的变量 item_data
仅存在于 get_info
函数的范围内。不过,您可以使用相同的变量名,并将函数的结果分配给它。
在您尝试设置项目格式的部分中也存在语法问题。
将您试过的部分替换为:
for product_url in get_links():
item_data = get_info(product_url)
data = "{0},{1},{2},{3}".format(*(item_data[item] for item in ('item_title','item_price','item_no','item_img')))
x.write(data)
我正在尝试编写一个程序,从 ebay 产品页面收集特定信息并将该信息写入文本文件。为此,我使用 BeautifulSoup 和 Requests,并且我正在使用 Python 2.7.9。
我主要使用本教程 (Easy Web Scraping with Python) 并进行了一些修改。到目前为止,一切都按预期工作,直到它写入文本文件。资料都写好了,只是不是我想要的格式。
我得到的是:
{'item_title': u'Old Navy Pink Coat M', 'item_no': u'301585876394', 'item_price': u'US .00', 'item_img': 'http://i.ebayimg.com/00/s/MTYwMFgxMjAw/z/Sv0AAOSwv0tVIoBd/$_35.JPG'}
我所希望的是一些更容易使用的东西。 例如:
New Shirt 5555555555 US .00 http://ImageURL.jpg
换句话说,我只想要刮掉的文本,而不是方括号、'item_whatever' 或 u'。
经过一番研究后,我怀疑我的问题与写入文本文件时的信息编码有关,但我不确定如何解决它。
到目前为止我已经尝试过了,
def collect_data():
with open('writetest001.txt','w') as x:
for product_url in get_links():
get_info(product_url)
data = "'{0}','{1}','{2}','{3}'".format(item_data['item_title'],'item_price','item_no','item_img')
x.write(str(data))
希望它能让数据更容易按照我想要的方式进行格式化。它只导致 "NameError: global name 'item_data' is not defined" 在 IDLE 中显示。
我也尝试过在不同的位置使用.split()
和.decode('utf-8')
,但只收到AttributeErrors或者书面结果没有改变。
这是程序本身的代码。
import requests
import bs4
#Main URL for Harvesting
main_url = 'http://www.ebay.com/sch/Coats-Jackets-/63862/i.html?LH_BIN=1&LH_ItemCondition=1000&_ipg=24&rt=nc'
#Harvests Links from "Main" Page
def get_links():
r = requests.get(main_url)
data = r.text
soup = bs4.BeautifulSoup(data)
return [a.attrs.get('href')for a in soup.select('div.gvtitle a[href^=http://www.ebay.com/itm]')]
print "Harvesting Now... Please Wait...\n"
print "Harvested:", len(get_links()), "URLs"
#print (get_links())
print "Finished Harvesting... Scraping will Begin Shortly...\n"
#Scrapes Select Information from each page
def get_info(product_url):
item_data = {}
r = requests.get(product_url)
data = r.text
soup = bs4.BeautifulSoup(data)
#Fixes the 'Details about ' problem in the Title
for tag in soup.find_all('span',{'class':'g-hdn'}):
tag.decompose()
item_data['item_title'] = soup.select('h1#itemTitle')[0].get_text()
#Grabs the Price, if the item is on sale, grabs the sale price
try:
item_data['item_price'] = soup.select('span#prcIsum')[0].get_text()
except IndexError:
item_data['item_price'] = soup.select('span#mm-saleDscPrc')[0].get_text()
item_data['item_no'] = soup.select('div#descItemNumber')[0].get_text()
item_data['item_img'] = soup.find('img', {'id':'icImg'})['src']
return item_data
#Collects information from each page and write to a text file
write_it = open("writetest003.txt","w","utf-8")
def collect_data():
for product_url in get_links():
write_it.write(str(get_info(product_url))+ '\n')
collect_data()
write_it.close()
你走在正确的轨道上。
您需要一个局部变量来将 get_info
的结果分配给。您尝试引用的变量 item_data
仅存在于 get_info
函数的范围内。不过,您可以使用相同的变量名,并将函数的结果分配给它。
在您尝试设置项目格式的部分中也存在语法问题。
将您试过的部分替换为:
for product_url in get_links():
item_data = get_info(product_url)
data = "{0},{1},{2},{3}".format(*(item_data[item] for item in ('item_title','item_price','item_no','item_img')))
x.write(data)