在Python中访问网站,你可以使用多种方法,以下是几种常见的方式:
1. 使用`os`模块调用系统命令:
import osos.system('C:/Program Files/Internet Explorer/iexplore.exe http://www.baidu.com')
2. 使用`webbrowser`模块打开网页:
import webbrowserwebbrowser.open('http://www.baidu.com', new=0, autoraise=True)
3. 使用`urllib`或`urllib2`库(Python 2.x)访问网页:
import urllib2url = 'http://www.python.org'req = urllib2.Request(url)page = urllib2.urlopen(req)for line in page:print(line)
4. 使用`httplib`库(Python 2.x),但请注意,`httplib`在Python 3.x中已经被重命名为`http.client`:
import httplibconn = httplib.HTTPSConnection("www.python.org")conn.request("GET", "/")response = conn.getresponse()print(response.status, response.reason)

5. 使用`requests`库(Python 3.x),这是访问网页的推荐方法之一:
import requestsresponse = requests.get('http://www.python.org')print(response.text)
6. 使用`BeautifulSoup`库解析网页内容(通常与`requests`库一起使用):
from bs4 import BeautifulSoupimport requestsresponse = requests.get('http://www.python.org')soup = BeautifulSoup(response.text, 'html.parser')print(soup.prettify())
7. 使用`selenium`库自动化浏览器操作(适用于需要模拟用户交互的情况):
from selenium import webdriverdriver = webdriver.Chrome()driver.get('http://www.baidu.com')time.sleep(5) 等待页面加载driver.quit()
选择哪种方法取决于你的具体需求,例如是否需要处理cookies、会话、表单提交等。`requests`和`BeautifulSoup`的组合在大多数情况下都能满足需求,并且易于使用。如果你需要更复杂的浏览器自动化,可以考虑使用`selenium`
