【问题标题】:Parsing Website (XML) for specific with Python and save to mysql使用 Python 解析网站 (XML) 并保存到 mysql
【发布时间】:2014-07-16 00:38:15
【问题描述】:

我想向 Flickr API 发送一个 REST 请求。响应如下所示(XML):

This XML file does not appear to have any style information associated with it. The 
document tree is shown below.

<rsp stat="ok">
<photos page="1" pages="974001" perpage="250" total="243500161">

<photo id="123" owner="1234" secret="123" server="1" farm="4" 
title="DSC01316" ispublic="1" isfriend="0" isfamily="0" views="0" tags="" 
latitude="47.825188" longitude="11.300722" accuracy="16" context="0" 
place_id="XT" woeid="123" geo_is_family="0" geo_is_friend="0" 
geo_is_contact="0" geo_is_public="1">
<description/>
</photo>

<photo id="123" owner="123" secret="123" server="1" farm="3" 
title="DSC01351" ispublic="1" isfriend="0" isfamily="0" views="0" tags="" 
latitude="47.825263" longitude="11.300891" accuracy="16" context="0" 
place_id="XT" woeid="123" geo_is_family="0" geo_is_friend="0" 
geo_is_contact="0" geo_is_public="1">
<description/>
</photo>

and so forth...

我想要 python 做的是解析网站的照片 ID、所有者、标题 等并提取信息并将其保存到 mysql 数据库中(已使用 phpadmin 设置)。

为了更好地理解:我有这张表,其中第一行是我的分类,第二行是从示例中提取的数据。

Photo ID    Owner    Secret    Server    Farm    Title    ispublic    isfriend    isfamily    ....
123         1234     123       1         4       DSC01316 1           0           0      

我开始使用它来提取信息。虽然它不起作用......

import xml.etree.ElementTree as ET
import requests

url="https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=5...b&per_page=250&accuracy=1&has_geo=1&extras=geo,tags,views,description%22"
page=requests.get(url)
data = page.text
root = ET.fromstring(data)
for x in root.Element.get('photo'):
    test = x.get('Photo ID', 'Owner', 'Secret' , 'Server' , 'Farm' , 'Title' , 'ispublic' , 'isfriend' , 'isfamily')
print (test)

#does not work. it says: AttributeError: 'Element' object has no attribute 'Element'

有什么想法吗? 我只是在寻找一个提示,我想自己写!请注意,我对 python 比较陌生,并且指向文档站点的链接对我不起作用。我对此知之甚少。我需要进一步解释。 谢谢!

【问题讨论】:

    标签: python mysql xml parsing screen-scraping


    【解决方案1】:

    BeautifulSoup4 让您更轻松地解析 xml/http 文档。通过pip install beautifulsoup4 安装软件包后尝试以下代码。

    from bs4 import BeautifulSoup
    
    xml = "..."
    soup = BeautifulSoup(xml)
    
    for photo in soup.find_all('photo'):
        print(photo.attrs['title'])
    

    然后你会得到,

    DSC01316
    DSC01351
    

    查看http://www.crummy.com/software/BeautifulSoup/bs4/doc/了解更多信息。

    【讨论】:

    • 我以为 bs 只适用于 html,而不适用于 xml?尝试您的代码会给我一个invalid syntax 错误并突出显示photo.attrs,确切地说是photo。我很确定我已经遇到过几次这个问题了......
    • 而 bs4 对其自身进行了描述,“Beautiful Soup 是一个 Python 库,用于从 HTML 和 XML 文件中提取数据。” :)
    • 对,我应该知道的。尝试调用此 url 会给我一条错误消息:我用它更新了我的帖子。
    • 哦,等等。我知道为什么会出现该错误消息。我解决了再试试
    猜你喜欢
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 2012-02-12
    • 2011-08-27
    • 1970-01-01
    • 2017-07-07
    • 2017-06-16
    相关资源
    最近更新 更多