在Python中,网络爬虫是一种用于从网站上抓取数据的程序。为了实现网络爬虫,你需要使用一些库和工具,如requests和BeautifulSoup。以下是一个简单的网络爬虫示例,用于抓取网站上的标题和链接:
requests和beautifulsoup4库。如果没有,请使用以下命令安装:pip install requests beautifulsoup4 web_scraper.py的Python文件,并在其中编写以下代码:import requests from bs4 import BeautifulSoup def get_page(url): response = requests.get(url) if response.status_code == 200: return response.text else: print(f"Error: Unable to fetch the page. Status code: {response.status_code}") return None def parse_page(html): soup = BeautifulSoup(html, "html.parser") titles = soup.find_all("h2") # 根据网页结构选择合适的标签 links = soup.find_all("a") for title, link in zip(titles, links): print(f"Title: {title.get_text().strip()}") print(f"Link: {link['href']}\n") def main(): url = input("Enter the URL of the website you want to scrape: ") html = get_page(url) if html: parse_page(html) if __name__ == "__main__": main() web_scraper.py文件,然后输入要抓取的网站URL。程序将输出页面上的标题和链接。注意:这个示例仅适用于具有特定HTML结构的网站。你需要根据要抓取的网站的实际HTML结构来修改parse_page函数中的代码。此外,如果需要处理JavaScript渲染的页面,可以考虑使用Selenium或Scrapy等工具。