【问题标题】:Getting zero results in web scraping using XPath使用 XPath 在 Web 抓取中获得零结果
【发布时间】:2015-12-25 01:34:43
【问题描述】:

我正在使用以下两个函数来抓取页面以获取歌曲的下载链接。函数get_song_details 抓取一个链接并找到歌曲标题和专辑,函数get_download_url 抓取另一个链接以找到作为参数传递的歌曲标题的链接。

import requests
from lxml import html
import time

def get_song_details(link):
    page = requests.get(link)
    tree = html.fromstring(page.content)

    # retrieve song title from page
    song = tree.xpath('//font[@class="general"]/b[2]/text()')
    if song:
        song = song[0].strip()
    else:
        raise ValueError("Song Title: Webpage structure has changed.")
    song = song.split("-")[0] if song.find("-") else song

    # retrieve album name from link
    tokens = link.split("/")
    album = tokens[5] if len(tokens) > 6 else None

    song_details = {
        "title": song,
        "album": album,
    }

    return song_details


def get_download_url(song_details):
    title = song_details["title"]
    album = song_details["album"]

    url = "http://www.songspk.site/indian/anjaana_anjaani_2010.html"
    print song_details, url
    page = requests.get(url)
    tree = html.fromstring(page.content)
    download_url = tree.xpath('//a[contains(text(), "{0}")]/@href'.format(title))

    return download_url

以下代码在执行时效果很好。它打印['http://www.songspk.link/link1/song1.php?songid=7753', 'http://www.songspk.link/link1/song1.php?songid=7759'] -

song_details = {
    "title": "Aas Paas Khuda",
    "album": "Anjaana Anjaani"
}
print get_download_url(song_details)

但是,当我执行以下代码 sn-p 时,即使 song_details 字典与上面硬编码的 sn-p 中的内容相同,我也会得到一个空列表。

song_details = get_song_details("http://www.glamsham.com/music/lyrics/anjaana-anjaani/aas-pass-khuda/1368/3089.htm")
print get_download_url(song_details)

我无法理解参数song_details 与上述代码 sn-p 中的标题相同,但即使它不起作用。

【问题讨论】:

标签: python xpath web-scraping


【解决方案1】:

其中一页似乎有错字。请注意,您获得的歌曲标题为Aas Pass Khuda,但在Songs.PK 页面上只有Aas Paas KhudaPassPaas.

【讨论】:

  • 实际上,我在链接http://www.songspk.link/indian/anjaana_anjaani_2010.html 上看到了Aas Paas Khuda,我正在尝试解析它。
  • 我在 get_song_details 函数中犯了一些错误(我不知道是什么),因为歌曲标题是在该函数中生成的。我是这么认为的,因为当我对相同的值进行硬编码时,它工作得非常好。
  • @GautamMishra 请重新阅读答案 - 从glamsham.com 中提取的歌曲名为“Aas Pass Khuda”,但在songspk 上只有“Aas Paas Khuda”。
  • 我现在意识到错字了。非常感谢您更正此问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 2013-11-23
相关资源
最近更新 更多