Очистка и анализ информации о цитировании из результатов поиска Google Scholar - PullRequest
0 голосов
/ 20 мая 2019

У меня есть список из примерно 20000 названий статей, и я хочу снять их количество цитирований с Google Golopar.Я новичок в библиотеке BeautifulSoup.У меня есть этот код:

import requests
from bs4 import BeautifulSoup

query = ['Role for migratory wild birds in the global spread of avian 
 influenza H5N8','Uncoupling conformational states from activity in an 
 allosteric enzyme','Technological Analysis of the World’s Earliest 
 Shamanic Costume: A Multi-Scalar, Experimental Study of a Red Deer 
 Headdress from the Early Holocene Site of Star Carr, North Yorkshire, 
 UK','Oxidative potential of PM 2.5  during Atlanta rush hour: 
 Measurements of in-vehicle dithiothreitol (DTT) activity','Primary 
 Prevention of CVD','Growth and Deposition of Au Nanoclusters on Polymer- 
 wrapped Graphene and Their Oxygen Reduction Activity','Relations of 
 Preschoolers Visual-Motor and Object Manipulation Skills With Executive 
 Function and Social Behavior','We Know Who Likes Us, but Not Who Competes 
 Against Us']

url = 'https://scholar.google.com/scholar?q=' + query + '&ie=UTF-8&oe=UTF- 
       8&hl=en&btnG=Search'

content = requests.get(url).text
page = BeautifulSoup(content, 'lxml')
results = []
for entry in page.find_all("h3", attrs={"class": "gs_rt"}):
    results.append({"title": entry.a.text, "url": entry.a['href']})

, но он возвращает только заголовок и URL.я не знаю, как получить информацию о цитировании из другого тега.Пожалуйста, помогите мне здесь.

Ответы [ 2 ]

1 голос
/ 20 мая 2019

Вместо того, чтобы находить все теги <h3>, я предлагаю вам поискать теги, содержащие как <h3>, так и цитату (внутри <div class="gs_rs>"), т.е. найти все теги <div class="gs_ri">.

Затемиз этих тегов вы сможете получить все, что вам нужно:

query = ['Role for migratory wild birds in the global spread of avian influenza H5N8','Uncoupling conformational states from activity in an allosteric enzyme','Technological Analysis of the World’s Earliest Shamanic Costume: A Multi-Scalar, Experimental Study of a Red Deer Headdress from the Early Holocene Site of Star Carr, North Yorkshire, UK','Oxidative potential of PM 2.5  during Atlanta rush hour: Measurements of in-vehicle dithiothreitol (DTT) activity','Primary Prevention of CVD','Growth and Deposition of Au Nanoclusters on Polymer- wrapped Graphene and Their Oxygen Reduction Activity','Relations of Preschoolers Visual-Motor and Object Manipulation Skills With Executive Function and Social Behavior','We Know Who Likes Us, but Not Who Competes Against Us']

url = 'https://scholar.google.com/scholar?q=' + query + '&ie=UTF-8&oe=UTF-8&hl=en&btnG=Search'

content = requests.get(url).text
page = BeautifulSoup(content, 'lxml')
results = []
for entry in page.find_all("div", attrs={"class": "gs_ri"}): #tag containing both h3 and citation
    results.append({"title": entry.h3.a.text, "url": entry.a['href'], "citation": entry.find("div", attrs={"class": "gs_rs"}).text})
1 голос
/ 20 мая 2019

Вам нужно зациклить список. Вы можете использовать сессию для эффективности. Ниже приведено описание для BS 4.7.1, которая поддерживает псевдокласс :contains для определения количества цитирований. Похоже, вы можете удалить селектор типа h3 из селектора css и просто использовать класс перед a, т.е. .gs_rt a. Если у вас нет 4.7.1. вместо этого вы можете использовать [title=Cite] + a для выбора количества цитирований.

import requests
from bs4 import BeautifulSoup as bs

queries = ['Role for migratory wild birds in the global spread of avian influenza H5N8',
         'Uncoupling conformational states from activity in an allosteric enzyme',
         'Technological Analysis of the World’s Earliest Shamanic Costume: A Multi-Scalar, Experimental Study of a Red Deer Headdress from the Early Holocene Site of Star Carr, North Yorkshire, UK',
         'Oxidative potential of PM 2.5  during Atlanta rush hour: Measurements of in-vehicle dithiothreitol (DTT) activity',
         'Primary Prevention of CVD','Growth and Deposition of Au Nanoclusters on Polymer-wrapped Graphene and Their Oxygen Reduction Activity',
         'Relations of Preschoolers Visual-Motor and Object Manipulation Skills With Executive Function and Social Behavior',
         'We Know Who Likes Us, but Not Who Competes Against Us']

with requests.Session() as s:
    for query in queries:
        url = 'https://scholar.google.com/scholar?q=' + query + '&ie=UTF-8&oe=UTF-8&hl=en&btnG=Search'
        r = s.get(url)
        soup = bs(r.content, 'lxml') # or 'html.parser'
        title = soup.select_one('h3.gs_rt a').text if soup.select_one('h3.gs_rt a') is not None else 'No title'
        link = soup.select_one('h3.gs_rt a')['href'] if title != 'No title' else 'No link'
        citations = soup.select_one('a:contains("Cited by")').text if soup.select_one('a:contains("Cited by")') is not None else 'No citation count'
        print(title, link, citations) 

Альтернатива для <4.7.1. </p>

with requests.Session() as s:
    for query in queries:
        url = 'https://scholar.google.com/scholar?q=' + query + '&ie=UTF-8&oe=UTF-8&hl=en&btnG=Search'
        r = s.get(url)
        soup = bs(r.content, 'lxml') # or 'html.parser'
        title = soup.select_one('.gs_rt a')
        if title is None:
            title = 'No title'
            link = 'No link'
        else:  
            link = title['href']
            title = title.text
        citations = soup.select_one('[title=Cite] + a')
        if citations is None:
            citations = 'No citation count'
        else:
             citations = citations.text
        print(title, link, citations)

Нижняя версия переписана благодаря комментариям @facelessuser. Верхняя версия оставлена ​​для сравнения:

Вероятно, было бы более эффективно не вызывать select_one дважды в одной строке оператора if. Пока построение шаблона кэшируется, возвращаемый тег не кэшируется. Я бы лично установил для переменной значение, возвращаемое select_one, а затем, только если переменная равна None, изменил бы ее на Нет ссылки или Нет заголовка и т. Д. Это не так компактно, но будет более эффективным

[...] всегда проверяет, является ли тег None:, а не только если тег: С селекторами это не имеет большого значения, так как они будут возвращать только теги, но если вы когда-нибудь сделаете что-то вроде для x в tag.descendants: вы получите текстовые узлы (строки) и теги, и пустая строка будет оценивать false, даже если это действительный узел. В этом случае безопаснее всего проверить None

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...