[英]Python HTML source code
我想編寫一個腳本,從源代碼中選擇一個特殊點並返回它。 (打印出來)
import urllib.request
Webseite = "http://myip.is/"
html_code = urllib.request.urlopen(Webseite)
print(html_code.read().decode('ISO-8859-1'))
這是我目前的代碼。 我只想打印網站提供的 IP 地址。 這個輸入我會用python打印出來(title="copy ip address")。
您可以使用jsonip返回一個 JSON 對象,您可以使用標准 Python 庫輕松解析該對象
import json
from urllib2 import urlopen
my_ip = json.load(urlopen('http://jsonip.com'))['ip']
import requests
from bs4 import BeautifulSoup
s = requests.Session()
r = s.get('http://myip.is/')
soup = BeautifulSoup(r.text, "html5lib")
myIP = mySoup.find('a', {'title': 'copy ip address'}).text
print(myIP)
這使用請求庫(您應該始終用於 HTTP 請求)來拉頁面,將內容提供給 BeautifulSoup,一個非常好的 HTML 解析器,並要求 BeautifulSoup 找到一個<a>
標簽,將屬性title
設置為'copy ip address',然后將該標簽的文本部分保存為myIP
。
您可以使用正則表達式來查找 IP 地址:
import urllib.request
import re
Webseite = "http://myip.is/"
html_code = urllib.request.urlopen(Webseite)
content = html_code.read().decode('ISO-8859-1')
ip_regex = r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}'
ips_found = re.findall(ip_regex, content)
print(ips_found[0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.