【问题标题】:Python XML BeautifulSoup get text of children nodesPython XML BeautifulSoup 获取子节点的文本
【发布时间】:2013-07-16 19:47:19
【问题描述】:

在以前的项目中,我从 XML 标记属性中抓取数据,但我不知道如何获取子 XML 节点的文本。该程序从文本文件中提取 id 并将它们插入到 url 中,然后对其进行解析。 XML如下:

<Article>
    <Sometag Owner="Steve" Status="online">
        <ID Version="1">231119634</PMID>
        <DateCreated>
            <Year>2012</Year>
            <Month>10</Month>
            <Day>10</Day>
        </DateCreated>

我想从DateCreated 的子标签中取出year monthday 文本

到目前为止,我有以下,没有运气

    link = "http://somelink.com/"+line.rstrip('\n')+"?id=xml&format=text"
    args = (curlLink + ' -L ' + link + ' -o c:\\temp.txt --proxy-ntlm -x http://myproxy:80 -k -U:') 
    sp = subprocess.Popen(args) #run curl
    sp.wait() #Wait for it to finish before proceeding
    xml_string = open(r'C:\temp.txt', 'r').read() #read in the temporary file
    os.remove(r'C:\temp.txt') # clean up
    soup = BeautifulSoup(xml_string)
    result = soup.find('DateCreated')
    if result is not None:
        date = result.children.get_text()
        g.write(date +"\n")

【问题讨论】:

  • 非常感谢无缘无故的反对

标签: python xml beautifulsoup


【解决方案1】:

有几种不同的方法可以从数据中获取信息:

year = int(date.Year.text)
month = int(date.Month.text)
day = int(date.Day.text)

date.text 将文本内容作为字符串提供给您。你应该使用什么取决于你真正需要什么。

【讨论】:

    猜你喜欢
    • 2016-08-18
    • 2012-08-04
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    相关资源
    最近更新 更多