首页 > 解决方案 > 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=c7lwAPTu__8J&astart=20

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)

需要高亮显示的源代码

标签: pythonbeautifulsouprequest

解决方案


您可以使用一点正则表达式和 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])

推荐阅读