1. 安装所需库:
pip install requests beautifulsoup4
2. 导入库:
import requestsfrom bs4 import BeautifulSoup
3. 发送HTTP请求获取网页内容:
url = 'http://example.com' 需要提取信息的网页地址response = requests.get(url)content = response.text

4. 使用BeautifulSoup解析网页内容:
soup = BeautifulSoup(content, 'html.parser')
获取网页标题title = soup.title.stringprint('网页标题:', title)获取所有的链接links = soup.find_all('a')for link in links:print('链接:', link.get('href'))获取指定元素的内容element = soup.find('div', class_='content')print('内容:', element.text.strip())
以上步骤展示了如何使用Python和BeautifulSoup库提取网页的基本信息。你可以根据需要修改选择器来定位不同的网页元素。如果需要处理更复杂的网页结构或者需要遵循网站的robots.txt规则,你可能需要更深入地了解HTML和CSS选择器,甚至使用JavaScript渲染引擎如Selenium。
