哪些大型网站用mysql,html网页制作房地产页面,摄影网站设计模板,wordpress不好用源码链接#xff1a; https://github.com/Niceeggplant/Single—Site-Crawler.git 一、项目概述
从指定网页中提取文章关键信息的工具。通过输入文章的 URL#xff0c;程序将自动抓取网页内容
二、技术选型与原理
requests 库#xff1a;这是 Python 中用于发送 HTTP 请求… 源码链接 https://github.com/Niceeggplant/Single—Site-Crawler.git 一、项目概述
从指定网页中提取文章关键信息的工具。通过输入文章的 URL程序将自动抓取网页内容
二、技术选型与原理
requests 库这是 Python 中用于发送 HTTP 请求的常用库。它能够模拟浏览器向网页服务器发送请求并获取网页的 HTML 文本内容。在本项目中我们利用它来获取目标文章网页的源代码为后续的信息提取提供基础数据。其使用方法非常简单只需调用 requests.get() 方法并传入目标 URL 和可选的请求头信息即可。例如
import requestsurl https://example.com/article
headers {User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
}
response requests.get(url, headersheaders)
html_text response.text这里设置请求头中的 User-Agent 是为了模拟浏览器访问避免一些网站对非浏览器请求的限制。
BeautifulSoup 库该库主要用于解析 HTML 和 XML 文档。它能够将复杂的网页结构转换为易于操作的 Python 对象方便我们通过标签、类名、ID 等属性定位和提取网页中的元素。在本项目中我们使用它来解析 requests 库获取到的 HTML 文本以提取文章的各种信息。使用时首先需要创建一个 BeautifulSoup 对象例如
from bs4 import BeautifulSoupsoup BeautifulSoup(html_text, html.parser)这里的 html.parser 是 Python 内置的 HTML 解析器也可以根据需要选择其他更强大的解析器如 lxml 解析器。
三、代码实现步骤
定义提取函数
import requests
from bs4 import BeautifulSoupdef fetch_article_info(url):headers {User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3}try:response requests.get(url, headersheaders)response.raise_for_status() soup BeautifulSoup(response.text, html.parser)这里定义了 fetch_article_info 函数它接受一个文章 URL 作为参数并在函数内部进行请求和解析的操作。
提取标题 title_element soup.find(h1)title title_element.get_text().strip() if title_element else 未找到通过 soup.find(h1) 查找网页中的 h1 标签通常文章标题会在这个标签内。如果找到则获取其文本内容并去除首尾空格如果未找到则将标题设为 未找到。
提取作者 authors []author_elements soup.find_all(div, class_authors)if not author_elements:author_elements soup.find_all(input, idauthors)for author_element in author_elements:author_links author_element.find_all(a)for link in author_links:authors.append(link.get_text().strip())authors , .join(authors) if authors else 未找到首先尝试通过查找类名为 authors 的 div 标签来获取作者信息如果未找到则查找 id 为 authors 的 input 标签。然后遍历找到