👉 "今天开启网络爬虫与Web自动化的学习之旅,探索如何利用Python操作网页"
概念说明:webbrowser模块用于打开浏览器并加载指定URL,简化了网页访问操作。
代码示例:
importwebbrowserwebbrowser.open('http://www.python.org') # 打开指定URL
小提示:可以指定浏览器控制器(如Chrome、Firefox),若未指定则使用系统默认浏览器。
概念说明:requests模块简化了向服务器发送HTTP请求的过程,方便获取网页内容。
代码示例:
importrequestsres=requests.get('https://automatetheboringstuff.com/files/rj.txt')res.raise_for_status() # 检查请求是否成功playfile=open('romeo_and_juliet.txt', 'wb')forchunkinres.iter_content(100000):playfile.write(chunk)playfile.close()
小提示:使用iter_content()方法分块写入文件,避免内存占用过高。
概念说明:BeautifulSoup模块用于解析HTML文档,提取所需数据。
代码示例:
frombs4importBeautifulSoupexample_file=open('example.html', 'r')example_soup=BeautifulSoup(example_file, 'html.parser')elems=example_soup.select('#author')print(elems[0].text) # 输出: Al Sweigart
小提示:select()方法支持CSS选择器语法,灵活定位HTML元素。
概念说明:selenium模块可自动化控制浏览器,执行复杂交互操作。
代码示例:
fromseleniumimportwebdriverbrowser=webdriver.Firefox() # 启动Firefox浏览器browser.get('http://inventwithpython.com')try:elem=browser.find_element_by_class_name('bookcover')print('Found element:', elem.tag_name)except:print('Element not found')
小提示:find_element_by_*系列方法用于定位页面元素,支持多种选择方式。
概念说明:结合requests和BeautifulSoup,编写脚本自动下载XKCD网站上的所有漫画。
代码示例:
importrequests, os, bs4url='http://xkcd.com'# 起始URLos.makedirs('xkcd', exist_ok=True) # 创建存储文件夹whilenoturl.endswith('#'):# 下载页面print(f'Downloading page {url}...')res=requests.get(url)res.raise_for_status()# 解析漫画URLsoup=bs4.BeautifulSoup(res.text, 'html.parser')comic_elem=soup.select('#comic img')ifcomic_elem:comic_url=comic_elem[0].get('src')# 下载漫画print(f'Downloading image {comic_url}...')img_res=requests.get(comic_url)img_res.raise_for_status()# 保存漫画img_file=open(os.path.join('xkcd', os.path.basename(comic_url)), 'wb')forchunkinimg_res.iter_content(100000):img_file.write(chunk)img_file.close()# 查找上一页链接prev_link=soup.select('a[rel="prev"]')[0]url='http://xkcd.com'+prev_link.get('href')print('Done.')
小提示:在循环中不断获取“上一页”链接,直到没有更多页面。
基础网页操作:使用webbrowser模块快速打开网页。
HTTP请求:利用requests模块发送请求并下载网页内容。
HTML解析:通过BeautifulSoup提取网页数据,支持CSS选择器。
浏览器自动化:借助selenium实现复杂浏览器交互。
实战项目:通过爬取XKCD漫画,综合运用网络编程技能。
你对网络爬虫最感兴趣的应用场景是什么?你认为在实际操作中需要注意哪些法律和道德问题?