Beautifulsoup给我没有值,而不是文本存在于HTML中

2024-03-28 10:37:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在为你做机器人Upwork.com网站所以我想得到“发布时间”的上升工作岗位,你可以看到下面

screenshot

但当我得到一个文本时,它返回一个None值

我使用的代码是:

from urllib.request import Request, urlopen

req = Request('https://www.upwork.com/o/jobs/browse/?q=scrap', headers={'User-Agent': 'Mozilla/5.0'})
html = urlopen(req).read()
soup = beautifulsoup(html)
for all_items in soup.select('.job-tile'):
    Time=all_items.select_one('time').text
    print(Time)

输出:

None

当我通过BeautifulSoup获得HTML时,我注意到HTML不包含在文本中,正如您在下面的HTML中看到的:

<span class="js-posted">Posted
  <time data-eo-relative="2018-04-24T06:11:41+00:00" datetime="2018-0424T06:11:41+00:00" itemprop="datePosted"> </time> 
</span>

有人能告诉我为什么文本没有用HTML显示吗?为什么我没有得到任何价值,而文本存在?你知道吗

注意:我在windows10上使用python3.6.5


Tags: 文本comnonetimerequesthtmlitemsall
1条回答
网友
1楼 · 发布于 2024-03-28 10:37:05

该站点使用Javascript根据<time>元素的属性显示相对时间。得到None是因为BeautifulSoup不加载或执行Javascript代码。你知道吗

您可以自己从属性中提取时间戳信息,并进行相同的计算,也可以使用全无头浏览器执行页面,然后提取信息。requests-html project可以帮助您实现后者,但这似乎有些过头了。你知道吗

提取datetime属性很简单;值是ISO8601格式的字符串,因此将其解析为Pythondatetime对象也很容易。如果必须有相对时间戳,则从datetime.now()中减去它,并格式化生成的datetime.timedelta()对象。或者使用^{} library创建一个漂亮的“人类”相对时间字符串,就像站点:

from datetime import datetime
import humanize

for elem in soup.select('.job-tile time["datetime"]'):
    # Python 3.6 %z only handles [+-]\d\d\d\d, not [+-]\d\d:\d\d, so remove
    # the last colon. Just hardcode the timezone, it's always UTC here anyway.
    dt_string = elem['datetime'].rpartition('+')[0] + '+0000'
    dt = datetime.strptime(dt_string, '%Y-%m-%dT%H:%M:%S%z')
    local_naive = dt.astimezone().replace(tzinfo=None)  # local time, naive
    print('Posted', humanize.naturaltime(local_naive))

一旦python3.7发布,您就可以简单地使用dt = datetime.fromisoformat(elem['datetime']),并让新的^{} class method为您处理解析。你知道吗

对于您的输入,这将产生:

>>> for elem in soup.select('.job-tile time["datetime"]'):
...     dt_string = elem['datetime'].rpartition('+')[0] + '+0000'
...     dt = datetime.strptime(dt_string, '%Y-%m-%dT%H:%M:%S%z')
...     local_naive = dt.astimezone().replace(tzinfo=None)  # local time, naive
...     print('Posted', humanize.naturaltime(local_naive))
...
Posted 8 minutes ago
Posted 35 minutes ago
Posted an hour ago
Posted an hour ago
Posted an hour ago
Posted an hour ago
Posted 2 hours ago
Posted 2 hours ago
Posted 2 hours ago
Posted 3 hours ago

相关问题 更多 >