【问题标题】:scraping the correct date hidden after script tag using beautifulsoup使用beautifulsoup刮掉隐藏在脚本标签后的正确日期
【发布时间】:2020-10-19 01:41:46
【问题描述】:

我想从网页上抓取日期,日期的文本(在脚本标签之后)是由 JavaScript 注入的:

<div class="row">
    <span class="LName"><a target="_blank" href="http://google.com">[me too]</a></span>
    <script language="Javascript" type="text/javascript">formatDate('2020,5,23,09,00,00',1)</script>6/23/2020&nbsp;10:00&nbsp;Tuesday
</div>

此标签上的正确日期是 2020 年 6 月 23 日。 我使用 beautifulsoup 创建了代码,但它返回错误的日期:

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}
r = requests.get(u, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')

我试试:

soup.select('div.row > script')[0].get_text()

返回:

"formatDate('2020,5,23,09,00,00',1)" 

和:

soup.select('div.row')[0].get_text()

返回:

"\n[me too] formatDate('2020,5,23,09,00,00',1)\n" 

当我使用 Chrome 检查标签时,我可以看到脚本标签后面的日期文本

当我执行时:

soup.select('div.row')

它返回没有日期文本的标签

JavaScript 注入的日期文本,我只需要使用 Beautifulsoup 来抓取它,而不是使用 selenium

【问题讨论】:

  • 您所追求的日期不在脚本标签内,不是吗?你可以在它前面看到&lt;/script&gt;
  • 是的,你是对的,我编辑了标题
  • 这能回答你的问题吗? get text after specific tag with beautiful soup
  • 文本是由 Javascript 注入的,我只需要使用 Beautifulsoup 来抓取它,而不是使用 selenium
  • 我会创建一个新问题

标签: python html web-scraping beautifulsoup css-selectors


【解决方案1】:

6/23/2020 的日期是 sibling&lt;script&gt; 标记。您可以使用.find_next_sibling(text=True) 获取此文本。

例如:

txt = '''<div class="row">
    <span class="LName"><a target="_blank" href="http://google.com">[me too]</a></span>
    <script language="Javascript" type="text/javascript">formatDate('2020,5,23,09,00,00',1)</script>6/23/2020&nbsp;10:00&nbsp;Tuesday
</div>'''

soup = BeautifulSoup(txt, 'html.parser')

d = soup.select_one('div.row > script').find_next_sibling(text=True).strip()
print(d)
print(d.split()[0])

打印:

6/23/2020 10:00 Tuesday
6/23/2020

【讨论】:

  • @KhaledKoubaa 可能您看到的文本是由 JavaScript 注入的,所以 BeautifulSoup 看不到它。试试print(soup) 看看有没有
  • 是的,我想是的,当我做 soup.select('div.row') 时,它会返回不带文本的标签,但是当我在 chrome 上使用 Inspect 时,我会看到文本
  • @KhaledKoubaa 所以是的,它是由 JavaScript 注入的 - 你可以尝试selenium 或其他方法(re 模块、json 模块等...)
  • 你可以帮我用 re(或其他)和 beautifulsoup 来做,而不需要 selenium 吗?拜托,我不喜欢使用硒
  • @KhaledKoubaa 为了不弄乱评论部分,我建议在 StackOverflow 上打开一个新问题。您可以在那里描述问题 + 输入有问题的 URL 和预期的输出。
猜你喜欢
  • 2021-01-04
  • 1970-01-01
  • 2021-10-18
  • 2021-03-17
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
相关资源
最近更新 更多