【发布时间】:2018-07-14 18:24:06
【问题描述】:
我在 python 中编写了一些代码来抓取一些电影名称以及与这些电影相关的一些附加信息。如果我考虑单独打印这两个项目,那么我到目前为止所写的内容都很好,例如位于
我脚本的中间部分和底部的print(addinfo)。
但是,当我尝试在底部将它们一起打印时,我只得到具有附加信息的电影名称(附加信息是从附加到每个电影名称的链接中检索的。问题是大多数电影名称不包含额外链接。)
例如,如果有 5 个电影名称,其中只有三个具有附加链接,那么当我将它们打印在一起时,我会得到三个电影名称和附加信息,而我应该打印 5 个电影名称。我希望打印那些没有额外信息的名称。我怎样才能解决这个问题?提前致谢。我认为站点地址和 html 信息无关紧要,因为代码运行良好。不过,我会粘贴完整的代码供您参考。
我尝试过的脚本:
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
URL = "https://in.bookmyshow.com/vizag/movies"
res = requests.get(URL)
soup = BeautifulSoup(res.text, 'lxml')
for item in soup.select(".card-container"):
movie = item.select_one(".__movie-name").text.strip()
print(movie) ####I do not wish to print it here. I expect to print both (movie and addinfo) together
blink = item.select_one(".book-button a")
if blink:
req = requests.get(urljoin(URL,blink['href']))
soup = BeautifulSoup(req.text,"lxml")
addinfo = ' '.join([item.select_one(".__venue-name").text.strip() for item in soup.select(".listing-info")])
print(movie,addinfo) ####if i print both of them together then I only get those movies which have items informations as well
【问题讨论】:
标签: python python-3.x web-scraping beautifulsoup