【问题标题】:Python request malfunctioning [closed]Python请求出现故障[关闭]
【发布时间】:2016-03-19 15:31:42
【问题描述】:

请帮助python。 我曾尝试使用 python 抓取网页。当我尝试在这个 url 中获取 iframe src 时,它只给了我一个 iframe 源。

这是我试图抓取的网页。


来源 1



来源 2


来源 2

这是我的python代码:

iframe = re.compile( '<iframe.*src="(.*?)"' ).findall( html )

这个只给了我 1 个 iframe。但是有 4 个 iframe

谢谢

【问题讨论】:

    标签: python iframe python-requests findall


    【解决方案1】:

    强烈推荐not parse HTML with regular expressions。对于 Python,Beautiful Soup 是一个广泛使用的选项,可以为您执行此解析。

    要提取您的 &lt;iframe/&gt; 来源,您可以使用类似的东西

    from bs4 import BeautifulSoup
    import requests
    
    resp = requests.get(url)
    soup = BeautifulSoup(resp.text)
    for frame in soup.findAll('iframe'):
        print(frame['src'])
    

    对于您指定的 URL,这将产生以下结果

    http://www.playhd.video/embed.php?vid=xxx
    http://mersalaayitten.com/embed/xxx
    http://www.playhd.video/embed.php?vid=xxx
    http://googleplay.tv/videos/kanithan?iframe=true
    //www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2Fkathaltamilmovie&width=600&height=188&colorscheme=light&show_faces=true&header=false&stream=false&show_border=true
    

    【讨论】:

      【解决方案2】:

      如果您只想将四个放在一起,您可以使用 BeautifulSoup css-selectors 从包含四个 iframe 的第二个表中获取数据,特别是 nth-of-type(2) 拉第二个表:

      from bs4 import BeautifulSoup
      import requests
      
      html = requests.get("http://kathaltamil.com/?v=Kanithan").content
      soup = BeautifulSoup(html)
      
      urls = [ifr["src"] for ifr in soup.select("table:nth-of-type(2)")[0].select("iframe")]
      

      这会给你四个:

      ['http://www.playhd.video/embed.php?vid=621', 
      'http://mersalaayitten.com/embed/3752', 
      'http://www.playhd.video/embed.php?vid=584', 
      'http://googleplay.tv/videos/kanithan?iframe=true']
      

      使用lxml 和 xpath 甚至更容易:

      import requests
      
      html = requests.get("http://kathaltamil.com/?v=Kanithan").content
      
      
      from lxml.etree import fromstring, HTMLParser
      
      xml = fromstring(html, HTMLParser())
      
      print(xml.xpath("//table[2]//iframe/@src"))
      

      这给了你同样的效果:

      ['http://www.playhd.video/embed.php?vid=621',
       'http://mersalaayitten.com/embed/3752', 
      'http://www.playhd.video/embed.php?vid=584', 
      'http://googleplay.tv/videos/kanithan?iframe=true']
      

      无论您选择什么都将是比您的正则表达式更好的选择。

      【讨论】:

        【解决方案3】:

        您似乎在第一个 .* 之后忘记了问号 (?) 正确的做法是:

        iframe = re.compile( '<iframe.*?src="(.*?)"' ).findall( html )
        

        不过,请记住,正则表达式并不是解析 html 网页的好方法。美汤、lxml、scrapy等库会更高效、更强大。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-09
          • 2016-07-19
          • 1970-01-01
          相关资源
          最近更新 更多