簡體   English   中英

使用 Python 從不同 url 列表中抓取文本

[英]Scrape text from a list of different urls using Python

我有一個不同 URL 的列表,我想從使用 Python 中抓取文本。 到目前為止,我已經設法構建了一個腳本,該腳本基於帶有關鍵字的 Google 搜索返回 URL,但是我現在想抓取這些 URL 的內容。 問題是我現在正在抓取整個網站,包括布局/樣式信息,而我只想抓取“可見文本”。 最終,我的目標是獲取所有這些 url 的名稱,並將它們存儲在 pandas DataFrame 中。 甚至可能包括某些名字被提及的頻率,但那是以后的事了。 到目前為止,下面是我的代碼的一個相當簡單的開始:

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import requests
from time import sleep
from random import randint
import spacy
import en_core_web_sm
import pandas as pd

url_list = ["https://www.nhtsa.gov/winter-driving-safety", "https://www.safetravelusa.com/", "https://www.theatlantic.com/business/archive/2014/01/how-2-inches-of-snow-created-a-traffic-nightmare-in-atlanta/283434/", "https://www.wsdot.com/traffic/passes/stevens/"]

df = pd.DataFrame(url_list, columns = ['url'])
df_Names = []

# load english language model
nlp = en_core_web_sm.load()

# find Names in text
def spacy_entity(df):    
    df1 = nlp(df)
    df2 = [[w.text,w.label_] for w in df1.ents]
    return df2

for index, url in  df.iterrows():
    print(index)
    print(url)
    sleep(randint(2,5))
    # print(page)
    req = Request(url[0], headers={"User-Agent": 'Mozilla/5.0'})
    webpage = urlopen(req).read()
    soup = BeautifulSoup(webpage, 'html5lib').get_text()
    df_Names.append(spacy_entity(soup))
df["Names"] = df_Names

為了使用 BeautifoulSoup 獲取可見文本,已經有這個答案: BeautifulSoup Grab Visible Webpage Text

一旦你得到你的可見文本,如果你想提取“名字”(我在這里假設你的名字是指“名詞”),你可以在這個其他答案上檢查 nltk package (或 Blob): Extracting all Nouns from a text使用 nltk 的文件

兩者都應用后,您可以將輸出提取到 pandas DataFrame 中。

注意:請注意,在給定 HTML 的情況下提取可見文本仍然是一個懸而未決的問題。 這兩篇論文可以比我更好地突出問題,並且它們都使用機器學習技術: https://arxiv.org/abs/1801.02607,https ://dl.acm.org/355476/24.1385436。 . 以及他們各自的github https://github.com/dalab/web2text , https://github.com/mrjleo/boilernet

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM