2013-01-15 63 views
0

我需要显示给定网站上所有ID的值。在urlliburllib2中是否有函数可以让我读取该站点,然后在“id =”之后打印值?任何帮助,将不胜感激。如何使用Python2.7在网页上显示所有ID的值?

+2

xpath'// * [string-length(@id)> 0]',遍历结果集,并吐出id属性值。 –

+0

@MarcB:你需要告诉他如何*先在数据上运行* xpath查询.. –

+0

谢谢,我正要问这个问题。感谢您迄今为止的评论。 =) – user1981656

回答

0

有明显的(但丑陋的)regex的解决方案,你在哪里得到的页面,使用urlliburllib2,或者更方便requests library,然后申请一个正则表达式,但我会建议pyquery包。 这就像jquery,但是对于python,用css选择器来获取节点。

对于您的问题:

from pyquery import PyQuery 

page = """ 
<html> 
    <body id='test'> 
    <p id='test2'>some text</p> 
    </body> 
</html> 
""" 

doc = PyQuery(page) 
for node in doc("*[id]").items(): 
    print(node.attr.id) 

会产生:

test 
test2 

并下载页面:

import requests 
page = requests.get("http://www.google.fr").text 

而且pyquery甚至can open urls,用urllibrequests

2

我会这样做使用BeautifulSoup和请求。我用一个简单的例子把这个页面放在一起,并发布在Github上。

请注意,这里的实际工作是在return语句中 - 大部分是样板。

from bs4 import BeautifulSoup as BS 
import requests as r 

def get_ids_from_page(page): 
    response = r.get(page) 
    soup = BS(response.content).body 

    return sorted([x.get('id') for x in soup.find_all() if x.get('id') is not None]) 

if __name__ == '__main__': 
    # In response to the question at the URL below - in short "How do I get the 
    # ids from all objects on a page in Python?" 
    ids = get_ids_from_page('http://stackoverflow.com/questions/14347086/') 

    for val in ids: 
     print val 
0

你可以使用正则表达式:

import re 

id_list = re.findall('id="(.*?)"', html_text) 

或者更复杂一点(以确保你出来只能从HTML标签解析它):

id_list = re.findall('<[^>]*? id="(.*?)"', html_text) 

这样只能解析特定类型的ID(匹配一些特殊模式)很容易

相关问题