如何使用Python从Wikipedia中删除链接

时间:2017-09-20 16:11:15

标签: python hyperlink screen-scraping wikipedia scrape

我正在尝试使用python从维基百科上的“海战”列表中删除所有战斗链接。麻烦的是我无法弄清楚如何将包含单词“/ wiki / Battle”的所有链接导出到我的CSV文件中。我习惯了C ++,所以python对我来说很陌生。有任何想法吗? 这是我到目前为止所拥有的......

from bs4 import BeautifulSoup
import urllib2

rootUrl = "https://en.wikipedia.org/wiki/List_of_naval_battles"


def get_soup(url,header):
    return
BeautifulSoup(
    urllib2.urlopen(urllib2.Request(url,headers=header)),'html.parser')

# soup settings    
url = rootUrl + item
header={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"}

soup = get_soup(url,header)

battle = soup.findAll("/wiki/Battle")

1 个答案:

答案 0 :(得分:0)

试试这个:

from bs4 import BeautifulSoup as bs
import requests

res = requests.get("https://en.wikipedia.org/wiki/List_of_naval_battles")
soup = bs(res.text, "html.parser")
naval_battles = {}
for link in soup.find_all("a"):
    url = link.get("href", "")
    if "/wiki/Battle" in url:
        naval_battles[link.text.strip()] = url

print(naval_battles)