【问题标题】:How to extract onClick url using beautifulsoup如何使用beautifulsoup提取onClick url
【发布时间】:2020-08-11 09:39:49
【问题描述】:

下面是需要提取的HTML代码

<div class="one_block" style="display:block;" onClick="location.href=\'/games/box.html
?&game_type=01&game_id=13&game_date=2020-04-19&pbyear=2020\';" style="cursor:pointer;">
<!-- \xe5\xb0\x8d\xe6\x88\xb0\xe7\x90\x83\xe9\x9a\x8
a\xe5\x8f\x8a\xe5\xa0\xb4\xe5\x9c\xb0 start -->
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="schedule_team">
<tr>

如何获得location.href 值?

试过了:

soup.findAll("div", {"onClick": "location.href"})

返回null

Desired Output:

/games/box.html?&game_type=01&game_id=13&game_date=2020-04-19&pbyear=2020

PS:有很多location.href

【问题讨论】:

  • 嗨,你试过正则表达式吗? import re from bs4 import BeautifulSoup soup.find_all('a', {'onClick': re.compile(r'location.href')})
  • 不,但为什么是regex?我觉得regex 占用了更多时间
  • 这只是一个建议...也许您可以尝试一下并使用分析器来跟踪性能问题
  • 什么没用?你仍然得到 None ?或者你有错误?
  • @johnrao07 想要的输出是什么?

标签: python html beautifulsoup


【解决方案1】:

如何使用.select() methodSoupSieve package 来运行 CSS 选择器

from bs4 import BeautifulSoup

html = '<div class="one_block" style="display:block;" onClick="location.href=\'/games/box.html?&game_type=01&game_id=13&game_date=2020-04-19&pbyear=2020\';" style="cursor:pointer;">' \
        '<!-- \xe5\xb0\x8d\xe6\x88\xb0\xe7\x90\x83\xe9\x9a\x8a\xe5\x8f\x8a\xe5\xa0\xb4\xe5\x9c\xb0 start -->' \
        '<table width="100%" border="0" cellspacing="0" cellpadding="0" class="schedule_team"><tr>'

soup = BeautifulSoup(html, features="lxml")
element = soup.select('div.one_block')[0]
print(element.get('onclick'))

使用 split 来获取只是 print(element.get('onclick').split("'")[1])

/games/box.html?&game_type=01&game_id=13&game_date=2020-04-19&pbyear=2020

【讨论】:

  • 输出是`location.href='/games/box.html?&game_type=01&game_id=25&game_date=2020-04-29&pbyear=2020';`,需要进一步的字符串处理来获取url,可以通过代码完成吗
  • 你需要什么输出?
  • 没关系我在你的操作上看到它,我稍后会尝试运行测试
  • 也许print(element.get('onclick').split("'")[1])
  • 非常感谢。我正在尝试从您的帖子中学习。它们是很好的资源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-21
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多