python - Web Crawling Google Scholar - 提取部分 HTML URL 以便能够抓取下一页/上一页
问题描述
我的任务是创建一个搜索引擎。我知道我需要创建一个可调整的 URL,我已经从按钮上的 onclick 属性中找到了我需要使用的源代码,但是随着页面的不同而变化。我需要我的 for 循环能够在每次页面更改以更新新 URL 时读取此内容。我在方括号中提供了我需要更改的 URL 示例。
我提供了一张图片,其中包含我需要的突出显示的源代码和部分未完成的代码。
对此的任何帮助将不胜感激。
https://scholar.google.co.uk/citations?view_op=view_org&hl=en&org=9117984065169182779&after_author= [新作者/用户代码]&astart=[新页码]
def main_page(max_pages):
page = 0
newpage = soup.find_all('button', {'onclick': ''})
while page <= max_pages:
url = 'https://scholar.google.co.uk/citations?view_op=view_org&hl=en&org=9117984065169182779&after_author='+str(newpage)'&astart='+str(page)
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for link in soup.findAll('a', {'href': '/citations?hl=en&user='}):
href = link.get('href')
print(href)
page += 10
main_page(1)
解决方案
您可以使用一点正则表达式和 urllib。
from bs4 import BeautifulSoup
import re
from urllib import parse
data = '''
<button onclick="window.location='/citations?view_op\x3dview_org\x26hl\x3den\x26org\x3d9117984065169182779\x26after_author\x3doHpYACHy__8J\x26astart\x3d30'">click me</button>
'''
PATTERN = re.compile(r"^window.location='(.+)'$")
soup = BeautifulSoup(data, 'html.parser')
for button in soup.find_all('button'):
location = PATTERN.match(button.attrs['onclick']).group(1)
parseresult = parse.urlparse(location)
d = parse.parse_qs(parseresult.query)
print(d['after_author'][0])
print(d['astart'][0])
推荐阅读
- php - 使用 Unoconv 将 docx 转换为 pdf 时出错
- ios - 视图控制器在 iPad 中呈现类似页面表
- javascript - 无法解析模块“./path_to_file”
- python - 我想在 GEKKO 数据的非线性回归中的给定点施加值和斜率约束,请帮助我
- javascript - 找不到模块 - 反应
- javascript - 如何在 Javascript 中仅设置 onClick 间隔?
- python - 解密密码学 fernet 编码以检查输入是否相同
- python - FastAPI + Jinja2 Web App 的 DRY 原则(前后端)
- datepicker - 没有年份的日期选择器
- react-testing-library - 如何使用 React 测试库“按元素查找”