在Python中使用Beautifulsoup遍历xml中的非href链接,并检索特定信息

2024-09-30 12:18:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个python初学者,刚开始学习使用Bsoup抓取站点。在

我试图从this site上的所有单独链接中提取联系人信息(地址、公司名称)。在

一般来说,我知道如何在典型的html源文件中检索href列表,但是由于这是一个xml,所以我只能将链接分离出来,以以下格式显示:

[u'http://www.agenzia-interinale.it/milano']

我不知道如何通过我的每一个公司的链接,但我不知道如何通过一个相关的代码。在

from bs4 import BeautifulSoup
import requests
import re

resultsdict = {}
companyname = []
url1 = 'http://www.agenzia-interinale.it/sitemap-5.xml'

html = requests.get(url1).text
bs = BeautifulSoup(html)
# find the links to companies
company_menu = bs.find_all('loc')
for company in company_menu:
    print company.contents

从这个链接列表中,它首先需要确定页面是否有联系人信息,然后如果它有,比如在this example中,那么它应该提取地址/公司名称。在

我相信我要查找的最终信息可以通过这个div过滤器隔离:

^{pr2}$

我试过放入一个嵌套循环,但无法使其工作。在

任何意见都非常感谢!在


Tags: import名称信息http列表链接地址html
2条回答

没有必要为此使用beauthoulsoup。该站点返回的是完全有效的XML,可以使用Python包含的工具进行解析:

import requests
import xml.etree.ElementTree as et

req = requests.get('http://www.agenzia-interinale.it/sitemap-5.xml')
root = et.fromstring(req.content)
for i in root:
    print i[0].text  # the <loc> text

根据您的请求,您希望从xml获取url,但您正在寻找格式化xml的css标记。。。走错了路。在

试试这个:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2 
from BeautifulSoup import BeautifulSoup

url1 = 'http://www.agenzia-interinale.it/sitemap-5.xml'

f = urllib2.urlopen(url1)

bs = BeautifulSoup(f)

for url in bs.findAll("loc"):
    print url.string

请注意,我使用的是findAll()方法,并查找“loc”标记,其中包含要检索的数据。在

相关问题 更多 >

    热门问题