【问题标题】:Extract a link from a webpage using Python使用 Python 从网页中提取链接
【发布时间】:2019-04-12 06:59:05
【问题描述】:

我有这个问题:我想从这个页面中提取每个项目的 URL,但我不知道该怎么做。我试图通过

提取它
projects = main_page.find_all_next('div', attrs={'class':'relative self-start'})

但我没有得到链接。我怎样才能通过它?提前感谢您对我的帮助。

【问题讨论】:

  • 添加代码块可能会有所帮助。所以我们看到了使用的孔设置和导入等。您确定动态加载的内容已经可用吗?

标签: python web-scraping beautifulsoup href


【解决方案1】:

此网站动态加载内容。所以你需要一些可以运行 javascript 的东西。有一个使用 selenium 访问网站的简单示例。

from selenium import webdriver
from bs4 import BeautifulSoup

url = "https://www.kickstarter.com/discover/categories/music"

dr = webdriver.Chrome() # or PhantomJS,Firefox
try:
    dr.get(url)
    main_page = BeautifulSoup(dr.page_source,"lxml")
    projects = main_page.find_all('div', {'class':'relative self-start'})
    project_showed = main_page.find_all("div",class_="bg-white black relative border-grey-500 border")
    print(len(projects))
except Exception as e:
    raise e

finally:
    dr.close()

但是如果你不能及时加载数据,你应该使用WebDriverWaitImplicit等待加载完成。 WebDriverWait and Implicit

【讨论】:

    【解决方案2】:

    javascript生成的链接,用BeutifulSoup获取不到,用Regex抓取javascript变量中的url

    import requests
    import re
    
    html = requests.get('https://www.kickstarter.com/discover/categories/music').text
    listURL = re.findall(r'"project":"([^"]+)', html)
    for url in listURL:
        print url
    

    【讨论】:

    • 通过这些步骤,我没有得到我想要的链接,但我得到了随机链接。我想要这个网页上每个项目的链接:kickstarter.com/discover/…
    • 它不是随机的,而是返回前 24 个项目 url,您需要使用端点 .../advanced?param.... 提取 json 以获得更多结果或查看此库 github.com/Dansc/pykick
    猜你喜欢
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2011-04-14
    • 2023-03-18
    • 1970-01-01
    • 2011-07-04
    相关资源
    最近更新 更多