阅读量:139
要使用Python进行网页抓取,您可以使用第三方库requests和BeautifulSoup。以下是一个简单的示例,说明如何使用这两个库获取网页内容:
- 首先,确保您已经安装了requests和beautifulsoup4库。如果尚未安装,可以使用以下命令安装:
pip install requests beautifulsoup4
- 然后,创建一个名为web_scraper.py的Python文件,并在其中编写以下代码:
import requests
from bs4 import BeautifulSoup
def get_webpage_content(url):
try:
response = requests.get(url)
response.raise_for_status() # 如果请求失败,将抛出HTTPError异常
response.encoding = response.apparent_encoding # 自动检测编码格式
return response.text
except requests.exceptions.RequestException as e:
print(f"Error fetching the webpage: {e}")
return None
def main():
url = input("Enter the URL of the webpage you want to scrape: ")
content = get_webpage_content(url)
if content:
soup = BeautifulSoup(content, 'html.parser')
print("Webpage content:")
print(soup.prettify())
if __name__ == "__main__":
main()
- 运行web_scraper.py文件,然后输入要抓取的网页URL。程序将输出网页的HTML内容。
注意:这个示例仅用于演示目的。在实际应用中,请确保遵守目标网站的robots.txt规则和相关法律法规。