在Python中访问网页通常有以下几种方法:
1. 使用 `urllib` 库:
import urllib.request
url = 'http://example.com'
response = urllib.request.urlopen(url)
html = response.read()
print(html)
2. 使用 `requests` 库(推荐,更简单方便):
import requests
url = 'http://example.com'
response = requests.get(url)
html = response.text
print(html)
3. 使用 `BeautifulSoup` 库解析网页(通常与 `requests` 库一起使用):
import requests
from bs4 import BeautifulSoup
url = 'http://example.com'
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
print(soup.prettify())
4. 使用 `webbrowser` 模块打开网页:
import webbrowser
url = 'http://example.com'
webbrowser.open(url)
5. 使用 `cx_Oracle` 库访问Oracle数据库(如果需要访问数据库而非网页):
import cx_Oracle
dsn = cx_Oracle.makedsn('your_host', 'your_port', service_name='your_service_name')
connection = cx_Oracle.connect('your_username', 'your_password', dsn)
cursor = connection.cursor()
cursor.execute('SELECT * FROM your_table')
result = cursor.fetchall()
for row in result:
print(row)
选择适合你需求的方法进行网页访问。