Python 网络爬虫-以下链接
请容忍我。我对Python很陌生,但我有很多乐趣。我正在尝试编写一个网络爬虫程序,它可以爬过上次丹麦公投的选举结果。我已经设法从主页上提取了所有相关链接。现在我希望Python跟踪92个链接中的每一个,并从每个页面收集9条信息。但是我太困了。希望你能给我一个提示 这是我的密码:Python 网络爬虫-以下链接,python,beautifulsoup,web-crawler,Python,Beautifulsoup,Web Crawler,请容忍我。我对Python很陌生,但我有很多乐趣。我正在尝试编写一个网络爬虫程序,它可以爬过上次丹麦公投的选举结果。我已经设法从主页上提取了所有相关链接。现在我希望Python跟踪92个链接中的每一个,并从每个页面收集9条信息。但是我太困了。希望你能给我一个提示 这是我的密码: import requests import urllib2 from bs4 import BeautifulSoup # This is the original url http://www.kmdvalg.d
import requests
import urllib2
from bs4 import BeautifulSoup
# This is the original url http://www.kmdvalg.dk/
soup = BeautifulSoup(urllib2.urlopen('http://www.kmdvalg.dk/').read())
my_list = []
all_links = soup.find_all("a")
for link in all_links:
link2 = link["href"]
my_list.append(link2)
for i in my_list[1:93]:
print i
# The output shows all the links that I would like to follow and gather information from. How do I do that?
这是我使用
lxml
的解决方案。它类似于beautifulsou
import lxml
from lxml import html
import requests
page = requests.get('http://www.kmdvalg.dk/main')
tree = html.fromstring(page.content)
my_list = tree.xpath('//div[@class="LetterGroup"]//a/@href') # grab all link
print 'Length of all links = ', len(my_list)
my_list
是一个包含所有链接的列表。现在您可以使用for循环在每个页面中获取信息
我们可以通过每个链接进行for循环。在每个页面中,您可以提取信息作为示例。这只适用于最上面的桌子
table_information = []
for t in my_list:
page_detail = requests.get(t)
tree = html.fromstring(page_detail.content)
table_key = tree.xpath('//td[@class="statusHeader"]/text()')
table_value = tree.xpath('//td[@class="statusText"]/text()') + tree.xpath('//td[@class="statusText"]/a/text()')
table_information.append(zip([t]*len(table_key), table_key, table_value))
对于页面下方的表格
table_information_below = []
for t in my_list:
page_detail = requests.get(t)
tree = html.fromstring(page_detail.content)
l1 = tree.xpath('//tr[@class="tableRowPrimary"]/td[@class="StemmerNu"]/text()')
l2 = tree.xpath('//tr[@class="tableRowSecondary"]/td[@class="StemmerNu"]/text()')
table_information_below.append([t]+l1+l2)
希望这有帮助 一种简单的方法是遍历URL列表并逐个解析它们:
for url in my_list:
soup = BeautifulSoup(urllib2.urlopen(url).read())
# then parse each page individually here
或者,您可以使用
这将是我解决你问题的办法
import requests
from bs4 import BeautifulSoup
def spider():
url = "http://www.kmdvalg.dk/main"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')
for link in soup.findAll('div', {'class': 'LetterGroup'}):
anc = link.find('a')
href = anc.get('href')
print(anc.getText())
print(href)
# spider2(href) call a second function from here that is similar to this one(making url = to herf)
spider2(href)
print("\n")
def spider2(linktofollow):
url = linktofollow
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')
for link in soup.findAll('tr', {'class': 'tableRowPrimary'}):
anc = link.find('td')
print(anc.getText())
print("\n")
spider()
它还没有完成。。。我只从表中得到了一个简单的元素,但是你得到了它的想法以及它应该如何工作。这是我的最终代码,它可以顺利工作。请让我知道我是否可以做得更聪明
import urllib2
from bs4 import BeautifulSoup
import codecs
f = codecs.open("eu2015valg.txt", "w", encoding="iso-8859-1")
soup = BeautifulSoup(urllib2.urlopen('http://www.kmdvalg.dk/').read())
liste = []
alle_links = soup.find_all("a")
for link in alle_links:
link2 = link["href"]
liste.append(link2)
for url in liste[1:93]:
soup = BeautifulSoup(urllib2.urlopen(url).read().decode('iso-8859-1'))
tds = soup.findAll('td')
stemmernu = soup.findAll('td', class_='StemmerNu')
print >> f, tds[5].string,";",tds[12].string,";",tds[14].string,";",tds[16].string,";", stemmernu[0].string,";",stemmernu[1].string,";",stemmernu[2].string,";",stemmernu[3].string,";",stemmernu[6].string,";",stemmernu[8].string,";",'\r\n'
f.close()
在第二个功能中,您可以使用findAll,使用您想要查找的td类的名称来代替查找('td')。您能在每个链接中提到更多关于您想要获取的9条信息吗?哇-你们真是太棒了!!我将不得不花一些时间试图理解你的解决方案。我一了解他们就回来。非常感谢@提提帕特:是的。看看这个子站点。我想获取“stemmeberettigede/可以投票的人数”、“Optalte stemmer/计票人”、“JA stemmer/投赞成票的人”、“NEJ stemmer/投反对票的人”、“Blanke stemmer/空白票”、“Ugyldige stemmer/无效票”和市政当局的名称(本例中为Assenskredsen)啊,我看到@Metods,我将很快更新我的解决方案。对于
lxml
,它基本上遍历每个html标记,您可以通过简单web浏览器上的inspect元素找到这些标记/text()
将抓取标记内的文本。这太棒了。我的脚本现在可以工作了,这要感谢你对我的URL列表进行迭代的评论。UPS-没有完成。我相信这一页上的所有其他建议都很酷,但我选择了我能理解的和平建议。谢谢这是我最后的代码,如果你有建议,让它更智能,请让我知道。我向你致以最诚挚的问候。
import urllib2
from bs4 import BeautifulSoup
import codecs
f = codecs.open("eu2015valg.txt", "w", encoding="iso-8859-1")
soup = BeautifulSoup(urllib2.urlopen('http://www.kmdvalg.dk/').read())
liste = []
alle_links = soup.find_all("a")
for link in alle_links:
link2 = link["href"]
liste.append(link2)
for url in liste[1:93]:
soup = BeautifulSoup(urllib2.urlopen(url).read().decode('iso-8859-1'))
tds = soup.findAll('td')
stemmernu = soup.findAll('td', class_='StemmerNu')
print >> f, tds[5].string,";",tds[12].string,";",tds[14].string,";",tds[16].string,";", stemmernu[0].string,";",stemmernu[1].string,";",stemmernu[2].string,";",stemmernu[3].string,";",stemmernu[6].string,";",stemmernu[8].string,";",'\r\n'
f.close()