发布时间:2025-12-10 23:03:20 浏览次数:1
爬虫:自动获取网络数据的程序。
Web页面结构:HTML、CSS、JavaScript等。
HTTP请求:客户端向服务器请求数据的方式。
HTTP响应:服务器返回给客户端的数据。
使用Python的requests库发送HTTP请求。
importrequestsurl="https://www.example.com"response=requests.get(url)
获取响应内容
html_content=response.text
使用BeautifulSoup库解析HTML内容。
frombs4importBeautifulSoupsoup=BeautifulSoup(html_content,"html.parser")
使用CSS选择器或其他方法提取数据。
title=soup.title.string
发送请求,获取简书网站首页HTML内容。
importrequestsfrombs4importBeautifulSoupurl="https://www.jianshu.com"response=requests.get(url)html_content=response.text
将数据存储为JSON格式。
importjsonwithopen("jianshu_articles.json","w",encoding="utf-8")asf:json.dump(article_info_list,f,ensure_ascii=False,indent=4)headers={"User-Agent":"Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/58.0.3029.110Safari/537.3"}response=requests.get(url,headers=headers)importtimetime.sleep(10)
try:response=requests.get(url,headers=headers,timeout=5)response.raise_for_status()exceptrequests.exceptions.RequestExceptionase:print(f"Error:{e}")importrequestsfrombs4importBeautifulSoupimportjsonimporttimedeffetch_jianshu_articles():url="https://www.jianshu.com"headers={"User-Agent":"Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/58.0.3029.110Safari/537.3"}try:response=requests.get(url,headers=headers,timeout=5)response.raise_for_status()exceptrequests.exceptions.RequestExceptionase:print(f"Error:{e}")returnhtml_content=response.textsoup=BeautifulSoup(html_content,"html.parser")articles=soup.find_all("p",class_="content")article_info_list=[]forarticleinarticles:title=article.h3.text.strip()author=article.find("span",class_="name").text.strip()link=url+article.h3.a["href"]article_info={"title":title,"author":author,"link":link}article_info_list.append(article_info)returnarticle_info_listdefsave_to_json(article_info_list,filename):withopen(filename,"w",encoding="utf-8")asf:json.dump(article_info_list,f,ensure_ascii=False,indent=4)if__name__=="__main__":article_info_list=fetch_jianshu_articles()ifarticle_info_list:save_to_json(article_info_list,"jianshu_articles.json")print("Jianshuarticlessavedto'jianshu_articles.json'.")else:print("FailedtofetchJianshuarticles.")为了更好地理解这个实战项目,我们需要了解一些基础概念和原理,这将有助于掌握Python的网络编程和爬虫技术。以下是一些基本的网络爬虫概念:
HTTP协议:超文本传输协议(HTTP)是一种用于传输超媒体文档(如 HTML)的应用层协议。HTTP协议被用于从Web服务器传输或发布到Web浏览器或其他客户端的数据。
HTML、CSS 和 JavaScript:HTML 是用来描述网页的一种语言。CSS 是用来表现 HTML 结构的样式。JavaScript 是网页编程的一种脚本语言,主要用于实现网页上的动态效果和与用户的交互。
DOM:文档对象模型(DOM)是一种跨平台的编程接口,用于处理 HTML 和 XML 文档。DOM将文档视为树形结构,其中每个节点代表一个部分(如元素、属性或文本)。
URL:统一资源定位符(URL)是用于指定互联网资源位置的一种字符串。
请求头(Request Headers):在HTTP请求中,请求头包含了关于客户端的环境、浏览器等信息。常见的请求头字段有:User-Agent、Accept、Referer 等。
响应头(Response Headers):在HTTP响应中,响应头包含了关于服务器的信息、响应状态码等信息。常见的响应头字段有:Content-Type、Content-Length、Server 等。
网络爬虫策略:有些网站会采取一些策略来阻止爬虫抓取数据,如:封禁IP、限制访问速度、使用 JavaScript 动态加载数据等。在实际应用中,我们需要根据这些策略采取相应的应对措施,如:使用代理IP、限制爬虫抓取速度、使用浏览器模拟库(如 Selenium)等。