Python獲取網(wǎng)頁(yè)數(shù)據(jù)的常用方法有以下幾種:
import urllib.request
url = 'http://www.example.com' # 網(wǎng)頁(yè)的URL
response = urllib.request.urlopen(url) # 發(fā)送HTTP請(qǐng)求并獲取響應(yīng)
data = response.read() # 讀取響應(yīng)的數(shù)據(jù)
print(data)
import requests
url = 'http://www.example.com' # 網(wǎng)頁(yè)的URL
response = requests.get(url) # 發(fā)送GET請(qǐng)求并獲取響應(yīng)
data = response.text # 獲取響應(yīng)的文本數(shù)據(jù)
print(data)
from bs4 import BeautifulSoup
html = '''
<html>
<head><title>Example</title></head>
<body>
<p>Hello, World!</p>
</body>
</html>
'''
soup = BeautifulSoup(html, 'html.parser') # 創(chuàng)建BeautifulSoup對(duì)象
p = soup.find('p') # 查找第一個(gè)<p>標(biāo)簽
print(p.text) # 輸出<p>標(biāo)簽的文本內(nèi)容
以上是獲取網(wǎng)頁(yè)數(shù)據(jù)的常用方法,根據(jù)實(shí)際需求和情況選擇合適的方法即可。