一、正则爬取论文网首页论文标题的示例

import requestsimport refrom bs4 import BeautifulSoupheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ''Chrome/83.0.4103.116 Safari/537.36'}def get_html(url):try:res = requests.get(url, headers=headers)res.raise_for_status()res.encoding = 'gbk'return res.textexcept:print('response error!')def paper_title(page):my_items = re.findall(r'(.*?)', page)print('paper count of main page:' + str(len(my_items))) # 用正则的findall得出首页所有论文的超链接数量for item in my_items:print(item)

二、主函数使用bs4的CSS选择器select()一样算出了论文数:

if __name__ == '__main__':url = 'https://www.lunwendata.com/'html = get_html(url)soup = BeautifulSoup(html, 'html.parser')size = len(soup.select('a[target="_blank"]'))# 用CSS选择器得出首页所有论文超链接数print('paper count of main page:' + str(size))paper_title(html)

三、输出结果得出用正则方法筛选准确率更高:

可以看到,用正则的方法筛选出的数量比bs4的select选择器筛选出的少了20个,证明正则的方法筛选数量的准确率更高。