簡體   English   中英

如何使用Python2.7在網頁上顯示所有ID的值?

[英]How do I show the value of all the ID's on a web page using Python2.7?

我需要顯示給定網站上所有ID的值。 urlliburllib2中是否有一個函數可以讓我讀取站點,然后僅在“ id =“之后打印值? 任何幫助,將不勝感激。

我會使用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

有一個顯而易見的(但很丑陋)的正則表達式解決方案,您可以使用urlliburllib2來獲取頁面,或者使用更方便的請求庫 ,然后應用正則表達式,但是我建議使用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甚至可以使用urllibrequests 來打開url

您可以使用正則表達式:

import re

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

或更復雜(以確保僅從HTML標記中解析出來):

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

這樣,僅解析特定類型的ID(匹配某些特殊模式)將很容易

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM