【问题标题】:How can I extract url links from IGN website如何从 IGN 网站提取 url 链接
【发布时间】:2017-05-13 18:14:00
【问题描述】:

我正在尝试提取此网页上评论的网址 http://uk.ign.com/games/reviews 然后在单独的选项卡中打开前 5 个

现在,我尝试了不同的选择来尝试获取正确的数据,但似乎没有返回任何内容。我似乎无法超越提取列表中每条评论的网址,更不用说在单独的标签中打开前 5 条了。

我在 Python IDE 中使用 Python 3

这是我的代码:

import webbrowser, bs4, requests, re

webPage = requests.get("http://uk.ign.com/games/reviews", headers={'User-
Agent': 'Mozilla/5.0'})

webPage.raise_for_status()

webPage = bs4.BeautifulSoup(webPage.text, "html.parser")

#Me trying different selections to try extract the right part of the page 
webLinks = webPage.select(".item-title")
webLinks2 = webPage.select("h3")
webLinks3 = webPage.select("div item-title")

print(type(webLinks))
print(type(webLinks2))
print(type(webLinks3))
#I think this is where I've gone wrong. These all returning empty lists. 
#What am I doing wrong?


lenLinks = min(5, len(webLinks))
for i in range(lenLinks):
    webbrowser.open('http://uk.ign.com/' + webLinks[i].get('href'))

【问题讨论】:

  • 运气好能找到这些链接吗?
  • 我可以找到网页上的所有链接,但我无法提取我想要的链接。 webLinks = webPage.find_all('a') 给了我页面上的所有链接现在我正在尝试使用“h3”类提取“item-title”下的链接。我试过 webItems = webPage.find_all('a', {'class' : "title"}) webby = webPage.find_all(class_="h3") 这些都不起作用,也许我应该使用一些 for 循环种类?

标签: python python-3.x web web-scraping


【解决方案1】:

使用 bs4、BeautifulSoup 和它返回的 soup 对象(您拥有 webPage,您可以调用:

webLinks = webPage.find_all('a')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

find_all 根据标题返回元素列表(在您的情况下,a。这些是 HTML 元素;要获取链接,您需要更进一步。您可以访问 HTML 元素的属性(在您的在这种情况下,您想要 href) 就像您想要 dict 一样:

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

请参阅BeautifulSoup getting href 了解更多详情。当然,docs

ps python 通常是用snake_case 而不是CamelCase 编写的:)

【讨论】:

  • 这行得通,我正在阅读 Beautiful Soup 文档的 find_all 部分,想知道如果我想定位网页上的特定链接,是否需要使用 find_parents() 或者我应该使用for 循环从原始 find_all('a') 语句中提取我想要的链接,就像你对 a['href'] 所做的那样?
  • 嗨!我很高兴它有效——我不确定你的下一个问题,但我认为你在正确的轨道上:find_parents/children 将返回一个对象,你可以再次调用find_all...无论如何,如果这是您正在寻找的答案,请将其标记为已接受,以便其他人以后可以找到它:)
猜你喜欢
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 2016-04-18
  • 1970-01-01
相关资源
最近更新 更多