要使用Python进行网页抓取,您可以使用第三方库requests和BeautifulSoup。以下是一个简单的示例,说明如何使用这两个库获取网页内容:
pip install requests beautifulsoup4
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()
注意:这个示例仅用于演示目的。在实际应用中,请确保遵守目标网站的robots.txt规则和相关法律法规。