re.compile(r'<a.*?href="(.*?)".*?title="(.*?)".*?>')是什么意思
时间: 2024-04-26 15:23:19 浏览: 196
这是一个 Python 中 re 模块的正则表达式,用于匹配 HTML 中的链接标签。具体来说,它的含义是:
- `re.compile`:将正则表达式编译成一个正则对象。
- `r'<a.*?href="(.*?)".*?title="(.*?)".*?>'`:正则表达式本体,其中:
- `<a` 匹配 `<a` 开始标签。
- `.*?` 匹配任意数量的字符,非贪婪模式(即尽可能少地匹配)。
- `href="(.*?)"` 匹配 `href` 属性的值,使用括号将匹配结果分组。
- `.*?` 同上,匹配 `title` 属性之前的任意字符。
- `title="(.*?)"` 匹配 `title` 属性的值,同样使用括号分组。
- `.*?>` 匹配剩余的标签内容,直到 `>` 结束标签。
- `(.*?)`:括号中的内容是一个分组,用于提取链接的 URL 和标题。
因此,这个正则表达式可以匹配形如 `<a href="url" title="title">text</a>` 的标签,并且提取其中的 URL 和标题。
相关问题
findLink = re.compile(r'<a title="(.*?)" href="(.*?)">') 如何提取第二个(.*?)
这个正则表达式 `findLink = re.compile(r'<a title="(.*?)" href="(.*?)">')` 是用于Python的re模块中的模式匹配,它寻找HTML标签 `<a>` 中的`href`属性。其中 `(.*?)` 是一个非贪婪的捕获组,它会匹配任何字符(`.*?`),直到遇到下一次出现的`>`, 即结束标签之前的内容。
`"(.*?)"` 的第一个括号 `()` 表示这是一个捕获组,而 `*?` 表示尽可能少地匹配前一个模式。所以,当运行该正则表达式并找到匹配项时,你可以通过索引来获取第二个`(.*?)`部分,也就是`href`属性的URL。
例如,在匹配结果对象 `match` 中,你可以像这样获取`href`值:
```python
match_obj = findLink.search(some_html_string)
if match_obj:
url = match_obj.group(2) # group(1)是title,group(2)是href
```
在这里,`group(2)` 就代表了第二个捕获组的内容,即`href`链接。
import requests import re # from bs4 import BeautifulSoup import matplotlib.pyplot as plt import numpy as np # import pandas as pd i = 1 lists = [0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250] title = [] year = [] country = [] score = [] number = [] for page in range(0, 226, 25): url = 'https://movie.douban.com/top250?start=' + str(page) + '&filter=' headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"} resp = requests.get(url=url, headers=headers) resp.encoding = "utf-8" pattern = re.compile( r'<div class="pic">.*? < img width="100" alt="(?P<title>.*?)".*?class="">.*?<a href="(?P<URL>.*?)" class="">.*?导演: (?P<director>.*?) .*?<br>.*?(?P<year>.*?) / (?P<country>.*?) .*?"v:average">(?P<score>.*?)</span>.*?<span>(?P<number>.*?)人评价</span>', re.S) pic_url = re.compile(r'< img width="100".*?src="(.*?)" class="">', re.S) pic_URl = pic_url.findall(resp.text) data2 = pattern.finditer(str(resp.text)) for url1 in pic_URl: file1 = open('films.pic\\' + str(i) + '.jpg', 'ab') Pic = requests.get(url1) file1.write(Pic.content) i = i + 1 file1.close() file2 = open('movie.text', 'a+', encoding='utf-8') for m in data2: if int(m['number']) / 100000 > 13: number.append(int(m['number']) / 100000) country.append(m['country']) year.append(m['year']) title.append(m['title']) score.append(m['score']) file2.write( '电影名:' + m['title'] + ', 导演:' + m['director'] + ', 年份:' + m['year'] + ', 国家:' + m['country'] + ', 评分:' + m[ 'score'] + ',评价人数:' + str(int(m['number']) / 100000) + ' 100k') file2.write('\n') print( '电影名:' + m['title'] + ', 导演:' + m['director'] + ', 年份:' + m['year'] + ', 国家:' + m['country'] + ', 评分:' + m[ 'score'] + ',评价人数:' + str(int(m['number']) / 100000) + ' 100k')
你的代码是用Python爬取豆瓣电影Top250页面的电影信息。其中使用了requests模块向网页发送请求,re模块提取信息,以及matplotlib和numpy模块进行数据可视化。具体而言,代码中通过循环访问Top250页面的不同分页,使用正则表达式匹配页面中的电影信息,并将其存储到title、year、country、score和number等列表中。同时,还将每部电影对应的海报图片下载到本地。最后,将电影信息写入到文件中,并打印输出。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
import re,tkinter,requests,threading,tqdm as tt root = tkinter.Tk() root.title('在线视频解析') root.geometry('500x590+550+350') headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0'} ac = tkinter.Listbox(root, width=50, height=20, font=('黑体', 12)) ac.grid(row=2, columnspan=10, sticky="n" + "s" + "w" + "e") def sousuo(): i = b1.get() ac.delete(0, 'end') def extract_music_info(content): p = '|' content = re.sub(p, '', content, flags=re.S) pattern = re.compile('subject.*?href="(.*?)">(.*?)
', flags=re.S) return pattern.findall(content) def search_music(): url = 'https://www.hifini.com/search-' + i + '-1.htm' response = requests.get(url=url, headers=headers) return response.text def update_listbox(music_list): for music in music_list: pppp = music[1] + ":" + music[0] ac.insert('end', pppp) content = search_music() music_list = extract_music_info(content) update_listbox(music_list) def xiazzi(): def download_music(): ppp = ac.get(ac.curselection()) pp = re.search('thread.*?htm', ppp) v = pp.group() url1 = 'https://www.hifini.com/' + v response = requests.get(url=url1, headers=headers) ppp = response.text l2 = re.search('<script>.*?title:..(.*?).,.*?author:.(.*?).,.*?url:..(.*?).,', ppp, flags=re.S) p = 'https://www.hifini.com/' + l2.group(3) response = requests.get(url=p, headers=headers, stream=True) # 设置 stream=True 以启用流式下载 total_size = int(response.headers.get('Content-Length')) music_name = '{}-{}.mp3'.format(l2.group(2), l2.group(1)) progress_bar = tt.tqdm(total=total_size, unit='B', unit_scale=True) # 创建进度条 with open(music_name, 'wb') as f: for data in response.iter_content(chunk_size=1024): progress_bar.update(len(data)) # 更新进度条 f.write(data) progress_bar.close() # 关闭进度条 print(music_name) threading.Thread(target=download_music).start() a1 = tkinter.Label(root, text='音乐下载器', anchor="center", font=('黑体', 24)) a1.grid(row=0, columnspan=10, sticky="n" + "s" + "w" + "e") b1 = tkinter.Entry(root, width=35, font=('黑体', 16), ) b1.grid(row=1, column=3, padx=15) search_button = tkinter.Button(root, text='搜索', command=sousuo) search_button.grid(row=1, column=4) download_button = tkinter.Button(root, text='下载', command=xiazzi) download_button.grid(row=3, column=4) root.mainloop() 将download_button带有下载行为的按钮添加进列表,![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
import requests import re url='https://bbs.hcbbs.com' html=requests.get(url) html.encoding='GBK' #读取网页源码 reg=r'(.*?)' #写出所需要的正则表达式 titre=re.compile(reg,re.I) #创建正则表达式对象 urls=titre.findall(html.text) print(urls) f=open('D://aaaaa.csv','a') for titu in urls: f.write(titu[0]+','+titu[1]+'\n') #csv文件以逗号分隔 f.close() 写出该段代码的设计步骤
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
# -- coding: utf-8 -- import urllib.request import re def getNovertContent(): url = 'http://www.quannovel.com/read/640/' req = urllib.request.Request(url) req.add_header('User-Agent', ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36') data = urllib.request.urlopen(req).read().decode('gbk') str1 = str(data) # 将网页数据转换为字符串 reg = r'(.*?)' reg = re.compile(reg) urls = reg.findall(str1) for url in urls: novel_url = url[0] novel_title = url[1] chapt = urllib.request.urlopen(novel_url).read() chapt_html = chapt.decode('gbk') reg = r'</script> (.*?)</script type="text/javascript">' reg = re.compile(reg, re.S) chapt_content = reg.findall(chapt_html) chapt_content = chapt_content[0].replace( " ", "") chapt_content = chapt_content.replace("
", "") print("正在保存 %s" % novel_title) with open("{}.txt".format(novel_title), 'w', encoding='utf-8') as f: f.write(chapt_content) getNovertContent()
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)