Search code examples
python-2.7pycharmstring-concatenation

Concatenation of 2 strings failing because of incompatible operands error returned by PyCharm


I'm trying to run the following code :

# -*- coding: utf8 -*-
import requests
from bs4 import BeautifulSoup
link = "https://www.emploi-public.ma/ar/index.asp?p="
number_of_jobs = 0
houceima = u"الحسيمة"
print type(houceima)
for i in range(1,3):
    page_link = link+str(i)
    print page_link
    emp_pub = requests.get(page_link)
    soup = BeautifulSoup(emp_pub.content,"lxml")
    for link in soup.find_all("a"):
        if houceima in link :
            print link

But I'm getting following error :

Traceback (most recent call last):
  File "scrape_houceima", line 9, in <module>
    page_link = link+str(i)
TypeError: unsupported operand type(s) for +: 'Tag' and 'str'

I'm using PyCharm. I stated my IDE because the same concatenation page_link = link+str(i) executed well in IDLE.
What could be the problem here ?


Solution

  • You re-used link in your code:

    link = "https://www.emploi-public.ma/ar/index.asp?p="
    

    and

    for link in soup.find_all("a"):
    

    The latter use replaces the first link reference, so it is no longer a string object but a Tag object.

    Don't mask variables like that, rename one or the other. Perhaps the first use could be named base_url?