【问题标题】:getting part from page source python regex从页面源 python regex 获取部分
【发布时间】:2018-11-14 12:57:09
【问题描述】:

我正在尝试使用正则表达式从页面中提取特定部分,但它不起作用。

这是我要从页面中提取的部分:

"publishedTimeText":{"runs":[{"text":"1 day ago","navigationEndpoint":{"clickTrackingParams":"CLQBEPS8AiITCPGhkIPt094CFc8SKgodd30BJSibHA==","commandMetadata":{"webCommandMetadata":{"url":"/channel/UCqwUrj10mAEsqezcItqvwEw/community?lb=Ugy4VG4gQFILnreq-Bd4AaABCQ","webPageType":"WEB_PAGE_TYPE_BROWSE"}}

到目前为止,我已经尝试过了:

import requests
import re

r = requests.get('http://rophoto.es/kha.txt')


mystrx = re.search(r'^{"publishedTimeText":.*"WEB_PAGE_TYPE_BROWSE"}}', html_source)

但它对我没有用。

【问题讨论】:

  • 尝试删除^{中的{

标签: python regex python-3.x


【解决方案1】:

这段代码怎么样:

import requests
import re

regex = r"\"publishedTimeText\":.*?\"WEB_PAGE_TYPE_BROWSE\"}}"
r = requests.get('http://rophoto.es/kha.txt')
html_source = r.content.decode('utf-8')

mystrx = re.search(regex, html_source, re.MULTILINE)
print(mystrx.group(0))
# "publishedTimeText":{"runs":[{"text":"1 day ago","navigationEndpoint":{"clickTrackingParams":"CLQBEPS8AiITCPGhkIPt094CFc8SKgodd30BJSibHA==","commandMetadata":{"webCommandMetadata":{"url":"/channel/UCqwUrj10mAEsqezcItqvwEw/community?lb=Ugy4VG4gQFILnreq-Bd4AaABCQ","webPageType":"WEB_PAGE_TYPE_BROWSE"}}

regex101 的详细信息:https://regex101.com/r/WJ82Ky/1

通过此链接:https://youtube.com/channel/UCqwUrj10mAEsqezcItqvwEw/community 您需要:
– pip 安装硒
– pip install webdriver_manager
然后使用下面的代码,它在我的电脑上运行良好:

import re
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

regex = r"\"publishedTimeText\":.*?\"WEB_PAGE_TYPE_BROWSE\"}}"

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://youtube.com/channel/UCqwUrj10mAEsqezcItqvwEw/community')
html_source = driver.page_source
driver.quit()

mystrx = re.search(regex, html_source, re.MULTILINE)
print(mystrx.group(0))
# "publishedTimeText":{"runs":[{"text":"2 days ago","navigationEndpoint":{"clickTrackingParams":"CLQBEPS8AiITCKisjoWO1t4CFVwlKgodcY4PXiibHA==","commandMetadata":{"webCommandMetadata":{"url":"/channel/UCqwUrj10mAEsqezcItqvwEw/community?lb=Ugy4VG4gQFILnreq-Bd4AaABCQ","webPageType":"WEB_PAGE_TYPE_BROWSE"}}

【讨论】:

  • 因为 youtube url 的结构与 rophoto url 不同。它没有像"publishedTimeText":{"runs"...这样的数据
  • 但是当我在 chrome 中查看页面源并将源复制粘贴到 rophoto 时它可以工作
  • 我还在请求 youtube url 时使用了 chrome useragent,但仍然无法正常工作
  • 你能帮忙吗?
  • 我为 youtube 链接添加了更多解决方案!查看我更新的帖子!
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 2020-02-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 2016-08-26
  • 2013-10-04
相关资源
最近更新 更多