import requests
import re
from bs4 import BeautifulSoup
headers = {
'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.text
except:
print('response error!')
def paper_title(page):
my_items = re.findall(r'<a href="(.*?)" target="_blank">(.*?)</a>', page)
print('paper count of main page:' + str(len(my_items))) # 用正则的findall得出首页所有论文的超链接数量
for item in my_items:
print(item)
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个,证明正则的方法筛选数量的准确率更高。