Python Scrapy 自定义爬取项xml格式

标签 python xml scrapy

我使用 scrapy 抓取网页,我希望以某种格式输出到 xml 文件,下面是我的代码。

项目类

class Item(Item):
# define the fields for your item here like:
    id = Field()
    name = Field()
    address = Field()
    birthdate = Field()
    review = Field()

蜘蛛类

class FriendSpider(BaseSpider):
# identifies of the Spider
name = "friend"
count = 0 
allowed_domains = ["example.com.us"]
start_urls = [
    "http://example.com.us/biz/friendlist/"
]
def start_requests(self):
    for i in range(0,1722,40):
        yield self.make_requests_from_url("http://example.com.us/biz/friendlist/?start=%d" % i)

def parse(self, response):

    response = response.replace(body=response.body.replace('<br />', '\n')) 
    hxs = HtmlXPathSelector(response)
    sites = hxs.select('//ul/li')
    items = []

    for site in sites:
        item = Item()
        self.count += 1
        item['id'] = str(self.count)
        item['name'] = site.select('.//div/div/h4/text()').extract()
        item['address'] = site.select('h4/span/text()').extract()
        item['review'] = ''.join(site.select('.//div[@class="review"]/p/text()').extract())
        item['birthdate'] = site.select('.//div/div/h5/text()').extract()

        items.append(item)
    return items

输出格式如下:

<?xml version="1.0" encoding="utf-8"?>
<items>
  <item>
     <id>1</id>
     <name><value>Keith</value></name>
     <review>txt............</review>
     <address><value>United States</value></address>
     <birthdate><value>1988-04-03</value></birthdate>
  </item>
  .....
<items>

如何自定义 xml 格式如下:删除值标签并将 id 移动到项目根。

<?xml version="1.0" encoding="utf-8"?>
<items>
  <friend id = "1">
     <name>Keith</name>
     <review>txt............</review>
     <address>United States</address>
     <birthdate>1988-04-03</birthdate>
  </friend>
  .....
<items>

最佳答案

对于您的问题,您可以获得列表中的一个,在 page 中显示或者编写您自己的 XML 序列化程序,例如,基于 OrderedDict 类型。抓取结束后,您可以简单地使用所需参数调用 serialize() 并获取 XML 文档。

关于Python Scrapy 自定义爬取项xml格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15861784/

相关文章:

从多个列表创建 Python Numpy 数组

c# - XSLT:如何从 XSL 转换中输出 '<' 和 '>'?

python - 如何根据scrapy中本周的日期获取上周作为开始日期和结束日期

python - 就地修改 Python 列表

python - 使用 python 运行 TRACE32

python - 使用 Matplotlib 和 numpy 绘制方程组

java - 将位图设置为具有特定高度的ImageView

java - 如何通过取消 xpath 来修复 xml 文档数据

python - 当我按 CSS 类过滤时,为什么 scrapy 和 beautifulsoup 都没有返回任何内容?

python - scrapy: 'module' 对象没有属性 'OP_SINGLE_ECDH_USE'