【问题标题】:Cleaning up data written from BeautifulSoup to Text File清理从 BeautifulSoup 写入文本文件的数据
【发布时间】:2015-04-10 03:21:52
【问题描述】:

我正在尝试编写一个程序,该程序将从 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 $25.00', 'item_img': 'http://i.ebayimg.com/00/s/MTYwMFgxMjAw/z/Sv0AAOSwv0tVIoBd/$_35.JPG'}

我希望的是可以更容易使用的东西。 例如:

New Shirt 5555555555 US $25.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))

希望它能让数据更容易以我想要的方式格式化。只是导致 IDLE 中显示“NameError: global name 'item_data' is not defined”。

我也尝试过在各个位置使用.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()

【问题讨论】:

    标签: python web-scraping beautifulsoup text-files python-requests


    【解决方案1】:

    你在正确的轨道上。 您需要一个局部变量来将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)
    

    【讨论】:

      猜你喜欢
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      • 2012-05-28
      相关资源
      最近更新 更多