将抓取结果保存到 Pandas Dataframe 中

欧比万科托比

我正在使用以下代码使用 Selenium 和 Beautiful Soup 抓取 Google Scholar 不同页面的一些信息。

我可以打印所有抓取的信息,但无法将结果保存到一个 Dataframe 中进行导出。

如何保存每个搜索结果的结果(标题、作者、链接、摘要)?

# Dataframe initialisieren
data = {
        "Titel": [],
        "Link" :[],
        "Authoren" : [] ,
        "Veröffentlichungsjahr" : [],
        "Abstract" :[] 
        }
df = pd.DataFrame(data)


# Ort wo Chromedriver gespeichert ist (lokal)
PATH = '/Applications/chromedriver'

driver = webdriver.Chrome(PATH)

# URL aufrufen
driver.get('https://scholar.google.de/')
time.sleep(5)

#Searchbar finden und ausfüllen
search = driver.find_element_by_id('gs_hdr_tsi')
search.send_keys('"circular economy"AND "Dlt" AND "Germany" AND "Sweden"')
time.sleep(5)
search.send_keys(Keys.RETURN)

## Anzahl Ergebnisse --> /10 ist die Anzahl der Klicks auf "weiter"
Anzahl = driver.find_element_by_id('gs_ab_md').text
x=re.findall(r'\d+', Anzahl)[0]
# y mal auf "Weiter" klicken lassen
y = int(int(x)/10)+1
print("Seitenanzahl:", y)
i=0

for i in range(2): #y
    # Schranke einbauen, damit Selenium solange pausiert bis Ergebnisse geladen sind

    page_source = driver.page_source
    soup = BeautifulSoup(page_source, 'lxml')
        
    for item in soup.select('[data-lid]'): 
            try: 
                print('----------------------------------------') 
       # print(item) 
                print(item.select('h3')[0].get_text()) 
                title = item.select('h3')[0].get_text()

                print(item.select('a')[0]['href'])
                link = item.select('a')[0]['href']

                print(item.select('.gs_a')[0].get_text()) 
                author = item.select('.gs_a')[0].get_text()

                txt = item.select('.gs_a')[0].get_text()
                print(re.findall(r'\d+', txt)[0])

                year = re.findall(r'\d+', txt)[0]
                print(item.select('.gs_rs')[0].get_text()) 

                abstract = item.select('.gs_rs')[0].get_text()

                data_2 = {
                "Titel" : title,
                "Link" : link,
                "Authoren" : author,
                "Veröffentlichungsjahr" : year,
                "Abstract" : abstract
                }
                
                df_new = pd.DataFrame(data_2)

                df = df.append(df_new, ignore_index=True)

                print('----------------------------------------') 
            except Exception as e: 
                #raise e
                print('---')
    # Random Wartezeit (2-15 Sekunden), bis nächste Seite aufgerufen wird, um IP-Blocks zu verhindern
    
    w = random.randint(1,14)
    time.sleep(w)
    try:
        driver.find_element_by_link_text('Weiter').click()
    except:    
        driver.quit()

    i+=1
        



科拉连

不要在循环期间创建设置数据帧。策略是将记录收集到字典列表中,最后创建您的数据框。

新代码(搜索# <- HERE

# Ort wo Chromedriver gespeichert ist (lokal)
PATH = '/Applications/chromedriver'

driver = webdriver.Chrome(PATH)

# URL aufrufen
driver.get('https://scholar.google.de/')
time.sleep(5)

#Searchbar finden und ausfüllen
search = driver.find_element_by_id('gs_hdr_tsi')
search.send_keys('"circular economy"AND "Dlt" AND "Germany" AND "Sweden"')
time.sleep(5)
search.send_keys(Keys.RETURN)

## Anzahl Ergebnisse --> /10 ist die Anzahl der Klicks auf "weiter"
Anzahl = driver.find_element_by_id('gs_ab_md').text
x=re.findall(r'\d+', Anzahl)[0]
# y mal auf "Weiter" klicken lassen
y = int(int(x)/10)+1
print("Seitenanzahl:", y)

records = []  # <- HERE
for i in range(2): #y
    # Schranke einbauen, damit Selenium solange pausiert bis Ergebnisse geladen sind

    page_source = driver.page_source
    soup = BeautifulSoup(page_source, 'lxml')
        
    for item in soup.select('[data-lid]'): 
            try: 
                print('----------------------------------------') 
       # print(item) 
                print(item.select('h3')[0].get_text()) 
                title = item.select('h3')[0].get_text()

                print(item.select('a')[0]['href'])
                link = item.select('a')[0]['href']

                print(item.select('.gs_a')[0].get_text()) 
                author = item.select('.gs_a')[0].get_text()

                txt = item.select('.gs_a')[0].get_text()
                print(re.findall(r'\d+', txt)[0])

                year = re.findall(r'\d+', txt)[0]
                print(item.select('.gs_rs')[0].get_text()) 

                abstract = item.select('.gs_rs')[0].get_text()

                records.append({  # <- HERE
                "Titel" : title,
                "Link" : link,
                "Authoren" : author,
                "Veröffentlichungsjahr" : year,
                "Abstract" : abstract
                })

                print('----------------------------------------') 
            except Exception as e: 
                #raise e
                print('---')
    # Random Wartezeit (2-15 Sekunden), bis nächste Seite aufgerufen wird, um IP-Blocks zu verhindern
    
    w = random.randint(1,14)
    time.sleep(w)
    try:
        driver.find_element_by_link_text('Weiter').click()
    except:    
        driver.quit()

df = pd.DataFrame(records)  # <- HERE

输出:

>>> df
                                               Titel  ...                                           Abstract
0  Shifting infrastructure landscapes in a circul...  ...  … [Google Scholar] [CrossRef]; Kirchherr, J.; ...
1  Demand-supply matching through auctioning for ...  ...  … 12, 76131 Karlsruhe, Germany cPolitecnico di...
2  Using internet of things and distributed ledge...  ...  … The authors were able to show how a combinat...
3  The impact of Blockchain Technology on the Tra...  ...  … In the broader sense, Blockchain is a Distri...
4  Assessing the role of triple helix system inte...  ...  … depends upon the successful diffusion of sev...
5  Circular Digital Built Environment: An Emergin...  ...  … For example, when searching for articles rel...
6  [PDF][PDF] Phillip Bendix (Wuppertal Institute...  ...  … Stadtreinigung Hamburg (Germany): AI image …...
7  Waste Management–A Case Study of Producer Resp...  ...  … A similar study in Germany reported an inter...
8  Blockchain in the built environment and constr...  ...  … changes in regulation can facilitate industr...

[9 rows x 5 columns]

>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 5 columns):
 #   Column                 Non-Null Count  Dtype
---  ------                 --------------  -----
 0   Titel                  9 non-null      object
 1   Link                   9 non-null      object
 2   Authoren               9 non-null      object
 3   Veröffentlichungsjahr  9 non-null      object
 4   Abstract               9 non-null      object
dtypes: object(5)
memory usage: 488.0+ bytes

现在您可以使用df.to_csv(...)导出您的数据。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将网页抓取结果加载到Pandas DataFrame中

将多个Pandas DataFrame保存到单个Excel文件中

如何将 API 数据保存到 Pandas DataFrame 中?

将Pandas DataFrame保存到Django模型

以最快的方式将一键编码的功能保存到Pandas DataFrame中

将DataFrame show()的结果保存到pyspark中的字符串

如何从多个网站页面将抓取的结果保存到CSV文件中?

将 pandas.DataFrame 索引保存到 txt 文件(Python)

将Pyspark Dataframe保存到没有标题的csv中

将数据保存到Spark中后,DataFrame变为空

将DataFrame保存到Spark中的TFRecords时出错

将循环结果保存到变量中?

将字典嵌套到Pandas DataFrame中

循环期间保存到Excel(Pandas DataFrame)

将pandas df保存到几个不同的CSV文件中

将pandas groupby对象保存到csv文件中

如何将抓取数据保存到CSV文件中?

将表(几页)抓取到 Pandas Dataframe

Pandas Dataframe的Web抓取

在 Pandas DataFrame 中抓取上一年的数据

在Pandas Dataframe中回收

在pandas中扩展dataFrame

将pandas ols回归结果保存到数据框

如何将抓取的抓取工具中的数据保存到变量中?

将值堆叠到Pandas DataFrame中的不同行中

将元组提取到 Pandas DataFrame 中的行中

如何将 pandas.DataFrame.to_csv 保存到网络链接?

将存储在pandas列中的数组转换为新的dataframe列,将结果数组值追加并映射到原始dataframe

如何将具有多个结果集的SQL Server存储过程的输出保存到Pandas的每个数据框中